我有一张 STL 地图:
std::map<std::string, std::vector<int> > my_map;
我有两个变量:
string name;
int age;
这些变量的值会发生变化,但基本上我想要做的是:
- 如果键名不存在,则创建键名并将年龄添加到向量。
- 否则,键名确实存在将年龄添加到向量。
最终,我将有一张地图,其中包含人名和人的年龄,这些人的名字存储在一个整数向量中。
我无法为我的生活找出语法来做到这一点。请帮忙 :(。
安德鲁
更新后就简单了
my_map[ "Daniel" ].push_back( 40 );
my_map[ name ].push_back( age );
无论密钥是否存在,都适用于这两种情况。
鉴于下面的地图:
std::map<std::string,int> mymap;
// Whether the key exists or not it will put something on the key.
// So, if it does not exist it will create it, and if it exists it will
// just replace it.
mymap["somestring"] = 50;
mymap["b_string"] = 100;
我认为这就是您所需要的,如果我不正确,请告诉我。另外,请记住建议:http ://en.cppreference.com
您总能找到 C++ 的 STL 函数的基本概念和大量示例。