踏雪失踪 发表于 2022-6-2 10:47:58

关于迭代器问题


程序报错: expression:map/set iterator not incrementable


我创建了一个map<int, int> , 想删除值为1的键值对,恰巧第一个键值对就符合要求。我猜想应该是迭代器跨界了。


附上代码:
#include <iostream>
#include <map>

using namespace std;

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

        map1 = 1;
        map1 = 0;
        map1 = 0;
        map1 = 1;
        map1 = 1;
        map1 = 1;
        map1 = 0;
        map1 = 1;
        map1 = 0;
        map1 = 0;
        map1 = 1;

        for (map<int, int>::iterator itor = map1.begin(); itor != map1.end(); itor++)
        {
                int key = itor->first;
                int value = itor->second;
                //如果键值对的值为1,则删除此键值对
                if (value == 1)
                {
                        itor = map1.erase(itor);
                        itor--;
                        continue;
                }
                cout << "key = " << key << ", value = " << value << endl;
        }

        return 0;
}

傻眼貓咪 发表于 2022-6-2 11:52:57

本帖最后由 傻眼貓咪 于 2022-6-2 17:22 编辑

自行删除解答

jhq999 发表于 2022-6-2 12:10:00

#include <iostream>
#include <map>

using namespace std;

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

      map1 = 1;
      map1 = 0;
      map1 = 0;
      map1 = 1;
      map1 = 1;
      map1 = 1;
      map1 = 0;
      map1 = 1;
      map1 = 0;
      map1 = 0;
      map1 = 1;

      for (map<int, int>::iterator itor = map1.begin(); itor != map1.end(); )
      {
            
                //如果键值对的值为1,则删除此键值对
                if (itor->second == 1)
                {
                        itor = map1.erase(itor);
                  
            
                }
                else
                {
                        cout << "key = " << itor->first << ", value = " << itor->second << endl;
                        itor++;
                }
      }

      return 0;
}
页: [1]
查看完整版本: 关于迭代器问题