我目前有以下 map
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”处修改的值)
最佳答案
除了评论中给出的信息:
如果你有一个大小和计数映射到一个字符串,命名大小和计数一些有意义的东西并使它成为一个结构:
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";
}
关于c++ - 根据键字符串使用迭代器更改嵌套映射的 int 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36631904/