简体   繁体   English

映射迭代器不可取消

[英]map iterator not dereferencable

I am getting compile error "map/set" iterator not dereferencable". What is going on here? 我收到了编译错误“映射/设置”迭代器无法取消引用”。这是怎么回事?

#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;
}

The map is empty, so m.begin() is equal to the past-the-end iterator and is therefore invalid. 映射为空,因此m.begin()等于过去的迭代器,因此无效。

You first have to insert elements somehow (you can also do that implicitly by using operator[] ) to make it useful. 首先,您必须以某种方式insert元素(也可以通过使用operator[]隐式地执行此operator[] )以使其有用。

Also, you cannot modify the key of an element like this. 同样,您不能像这样修改元素的键。 You would have to remove ( erase ) the element from the map and insert a new one with the new key. 您将必须从地图上删除( erase )该元素,然后使用新键插入一个新元素。

Here's an example about that: 这是关于此的示例:

#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;
}

Your map 's empty! 您的map是空的! What your iterator is pointing to is undefined. 您的迭代器指向的对象是不确定的。

What you wanted to do is 你想做的是

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

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

Here you have not assign any value. 在这里您没有分配任何值。 and you can not change the key of itr->first of it. 并且您不能更改itr->first的密钥。 It can be read only. 它只能是只读的。 But you can edit itr->second . 但是您可以编辑itr->second

map<int, int> m;
    m[10]=0;
    map<int, int>::iterator itr=m.begin();


      itr->second=10;
    cout << itr->first << " " << itr->second;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM