我已经执行了以下代码:
#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 tables;
// Schema table
tables["table_name"]["row_id"]["field_name"] = "value";
}
我想修改 typedef 以将“row_id”作为数字索引和任何类型的值(一种自动检测)。我应该怎么做才能实现这样的目标?
tables["table1"][0]["field1"] = "value of any type";
最佳答案
数字索引很简单,只需将 std::string
替换为 int
即可。 “任何类型的值”可能很难获得正确的 C++,如果不小心操作,可能会导致问题。您可以使用 void *
(坏)或 union
(好),但更好的选择可能是一些变体实现,例如boost::variant ,所以 typedef
会读取,例如:
typedef std::map<std::string, std::map<int, std::map<std::string, boost::variant<int, std::string> > > > SCHEMA;
关于c++ - map 中任何类型的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20369419/