c++ - 根据键字符串使用迭代器更改嵌套映射的 int 值

标签 c++ dictionary nested key increment

我目前有以下 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/

相关文章:

C++:检查 vector 中的元素是否大于另一个具有相同索引的元素的有效方法?

C++ 关闭窗口而不是应用程序

python "TypeError: ' numpy.float6 4' object cannot be interpreted as an integer"

c++ - 使用参数从基函数指针调用基方法

c++ - OpenCV 3 中的神经网络权重

python - 我应该如何合并两个字典而不覆盖相同的键?

python - 如何合并列表中具有相等值的字典和不相等的连接值并将其他字段保留在字典中?

python - 如何根据字典列字段列表中的键值对过滤 DataFrame 行?

php - MySQL在where子句中进行条件查询

javascript - 使用 forEach 访问数组内的对象值?