从2级3级地图获取所有键

时间:2013-12-04 01:56:29

标签: c++ map

#include <string>
#include <map>
#include <vector>

typedef std::map<std::string, std::map<std::string, std::map<std::string, std::string> > > SCHEMA;

int main() {
    SCHEMA schema;

    // Schema table
    schema["table1"]["field1"]["type"] = "int";
    schema["table1"]["field2"]["type"] = "bool";
    schema["table2"]["field1"]["type"] = "int";
}

如何获取table1的字段名称?

我想有这样的事情:

fields = array(
 0 => "field1",
 1 => "field2"
)

1 个答案:

答案 0 :(得分:2)

您可以使用简单的for范围循环(C ++ 11)运行所有键:

std::vector<std::string> fields;
for (const auto& f : schema["table1"])
    fields.emplace_back(f.first);

或者,如果您无法访问C ++ 11功能,请使用迭代器:

std::vector<std::string> fields;
for (SCHEMA::const_iterator it = schema["table1"].cbegin(); it != schema["table1"].cend(); ++it)
    fields.push_back(it->first);