我目前有以下地图
typedef map<int, int> inner;
map<string, inner> example;
example["hello"][1] = 100;
example["hi"][2] = 200; //need to increment 2 to 3, and increase by 200
example["bye"][3] = 300;
example["ace"][4] = 400;
我想要做的是修改内部地图的值,我目前正在尝试以下
int size; //second int in inner map
int count; //first int in inner map
for (map<string, inner>::iterator it = example.begin(); it != example.end(); it++)
{
cout << it->first << " " ;
for (inner::iterator it2 = it->second.begin(); it2 != it->second.end(); it2++)
{
if (it->first.compare("hi")) //if at key "hi"
{
count = it2->first + 1;//increment by one
size = it2->second + 200;//add 200
example.erase("hi"); //remove this map entry
example["hi"][count] = size; //re-add the map entry with updated values
}
}
我尝试过几种不同的方法,但我确实觉得我不理解指针是如何工作的。我的输出显示计数值为2,大小为300(在键“hello”处修改的值)
答案 0 :(得分:0)
除了评论中提供的信息外:
如果您将大小和数量映射到字符串,请为大小命名并计算有意义的内容并使其成为结构:
struct Stats {
int size;
int count;
};
std::map<std::string, Stats> example;
example["hello"] = {1, 100};
example["hi"] = {2, 200};
如果您想在键“hi”找到值:
auto it = example.find("hi");
if (it != example.end()) {
++it->second.count;
it->second.size += 200;
}
如果要打印所有元素:
for (auto& i : example) {
std::cout << i.first << " = {"
<< i.second.size << ", "
<< i.second.count << "}\n";
}