c++ - 从 3 级 map 的第 2 级获取所有键

标签 c++ dictionary

#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";
}

如何获取表 1 的字段名称?

我想要这样的东西:

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

最佳答案

您可以使用简单的 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);

关于c++ - 从 3 级 map 的第 2 级获取所有键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20365392/

相关文章:

python - 如何在 Python 中将定义的字典传递给 **kwargs?

python - 在循环内将项目添加到字典

c++ - IntelliJ-CLion : What should I do to use input text file?

c++ - 请求 ‘insert’中的成员 ‘x’,非类类型

php - 帮助将 C++ 移植到 PHP 代码

mongodb - 从对象数组删除键值时出错

java - 如何引用实时 map 值

java - 如何将元组添加为(键,元组)映射的值?

c++ - 双端队列 : map<. 的问题 ..,双端队列 <>> 失败,但 vector 和列表不是?

c++ - 自定义迭代器范围函数无效输出