c++ - map 迭代器不可取消引用

标签 c++ dictionary

我收到编译错误“map/set”iterator not dereferencable”。这是怎么回事?

#include<iostream>
#include<map>

using namespace std;

int main(){
    map<int, int> m;
    map<int, int>::iterator itr=m.begin();

    itr->first = 0;
    itr->second = 0;

    cout << itr->first << " " << itr->second;
    return 0;
}

最佳答案

映射为空,因此 m.begin() 等于尾后迭代器,因此无效。

你首先必须insert元素以某种方式(您也可以通过使用 operator[] 隐式地做到这一点)使其有用。

此外,您不能像这样修改元素的键。您必须从 map 中删除 (erase) 元素并使用新键插入一个新元素。

这是一个例子:

#include<iostream>
#include<map>

using namespace std;

int main(){
    map<int, int> m;

    // insert element by map::insert
    m.insert(make_pair(3, 3));

    // insert element by map::operator[]
    m[5] = 5;

    std::cout << "increased values by one" << std::endl;
    for(map<int, int>::iterator it = m.begin(); it != m.end(); ++it)
    {
        it->second += 1;
        cout << it->first << " " << it->second << std::endl;
    }

    // replace an element:        
    map<int, int>::iterator thing = m.find(3);
    int value = thing->second;
    m.erase(thing);
    m[4] = value;

    std::cout << "replaced an element and inserted with different key" << std::endl;
    for(map<int, int>::iterator it = m.begin(); it != m.end(); ++it)
    {
        cout << it->first << " " << it->second << std::endl;
    }

    return 0;
}

关于c++ - map 迭代器不可取消引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33674588/

相关文章:

excel - 同时打印两个独立字典的键

字典列表的 Python 集合计数器

javascript - 为什么 JavaScript 字典键不能使用 myDict.123 语法以数字开头?

python - 在递增现有值的同时向字典添加新键

c++ - std::is_same 和 std::get 在一起

c++ - C++中变量和指针的区别

python - 从 DF 列将值插入字典 - Pandas (Python)

c++ - 函数后的分号

c++ - 如果 cin 中没有输入任何内容,如何停止递归?

c++ - Boost.Program_Options : When <bool> is specified as a command-line option, 什么是有效的命令行参数?