有没有办法用schema.liczby
之类的内容替换schema.studenci
和schema.($variable)
?在这种情况下,避免重复代码执行相同的操作只会针对不同的结构。
string getFieldType(string field_name, SCHEMA schema, string table)
{
if (table == "liczby")
{
for (int i = 0; i < schema.liczby.integers.size(); i++)
{
if (schema.liczby.integers[i] == field_name)
{
return "int";
}
}
for (int i = 0; i < schema.liczby.strings.size(); i++)
{
if (schema.liczby.strings[i] == field_name)
{
return "string";
}
}
for (int i = 0; i < schema.liczby.doubles.size(); i++)
{
if (schema.liczby.doubles[i] == field_name)
{
return "double";
}
}
for (int i = 0; i < schema.liczby.booleans.size(); i++)
{
if (schema.liczby.booleans[i] == field_name)
{
return "double";
}
}
}
else if (table == "studenci")
{
for (int i = 0; i < schema.studenci.integers.size(); i++)
{
if (schema.studenci.integers[i] == field_name)
{
return "int";
}
}
for (int i = 0; i < schema.studenci.strings.size(); i++)
{
if (schema.studenci.strings[i] == field_name)
{
return "string";
}
}
for (int i = 0; i < schema.studenci.doubles.size(); i++)
{
if (schema.studenci.doubles[i] == field_name)
{
return "double";
}
}
for (int i = 0; i < schema.studenci.booleans.size(); i++)
{
if (schema.studenci.booleans[i] == field_name)
{
return "double";
}
}
}
}
答案 0 :(得分:1)
我们可以重构您的代码。有很多方法可以给这只猫上皮。我认为std::map
让事情变得非常简单,但是YMMV。我认为你应该改变第二个地图的类型,这样你就可以存储类型+值(boost:variant
或者多态设置可能会很好用。)这段代码只是一个起点。
#include <string>
#include <map>
#include <vector>
typedef std::map<std::string, std::map<std::string, std::string>> SCHEMA;
int main() {
SCHEMA schema;
// Schema table
schema["liczby"]["wartosc"] = "column";
schema["liczby"]["wartość"] = "int";
schema["studenci"]["indeks"] = "column";
schema["studenci"]["imie"] = "column";
schema["studenci"]["nazwisko"] = "column";
schema["przedmioty"]["id"] = "column";
schema["przedmioty"]["nazwa"] = "column";
schema["przedmioty"]["semestr"] = "column";
schema["sale"]["nazwa"] = "column";
schema["sale"]["rozmiar"] = "column";
schema["sale"]["projektor"] = "column";
schema["sale"]["powierzchnia"] = "column";
}
std::string getFieldType(std::string field_name, SCHEMA& schema, std::string table) {
return schema[table][field_name];
}
答案 1 :(得分:0)
没问题。您的LICZBY_SCHEMA
,STUDENCI_SCHEMA
,PRZEDMIOTY_SCHEMA
和SALE_SCHEMA
相同,因此我们将其全部替换为BASIC_SCHEMA
。然后代码变得更加简单:
struct BASIC_SCHEMA
{
vector<string> columns;
vector<string> integers;
vector<string> strings;
vector<string> booleans;
vector<string> doubles;
};
struct SCHEMA
{
BASIC_SCHEMA liczby;
BASIC_SCHEMA studenci;
BASIC_SCHEMA przedmioty;
BASIC_SCHEMA sale;
};
string getFieldType(string field_name, SCHEMA schema, string table)
{
BASIC_SCHEMA subSchema;
if (table == "liczby")
subSchema = schema.liczby;
else if (table == "studenci")
subSchema = schema.studenci;
else
return("");
for (unsigned int i = 0; i < subSchema.integers.size(); i++)
{
if (subSchema.integers[i] == field_name)
{
return "int";
}
}
...
}
我们可以使它更简洁,例如find(...)
,但这是另一个故事。