如何在c ++中实现数据结构,其行为类似于具有键值对的Javascript对象。
var a = {
"key1" : value1,
"key2" : value2,
}
console.log(a["key1"]);
答案 0 :(得分:2)
如果您想要键值对列表,std::map可以是一个选项:
std::map<std::string,int> key_value_pair_list;
key_value_pair_list.emplace("key1",5);
key_value_pair_list.emplace("key2,10);
std::cout << key_value_pair_list["key1"];
答案 1 :(得分:2)
可以使用std::map
,例如:
#include <iostream>
#include <string>
#include <map>
int main()
{
std::map<std::string, int> a{ {"key1", 1},{"key2", 2},{"key3", 3} };
std::cout << a["key2"] << std::endl;
return 0;
}