书法字典:https://www.shufadict.com

正确使用STL-MAP中Erase函数

一切尽在代码中。

复制代码
#include <iostream>
#include <map>
#include <string>
using namespace std ;

int main(void) 
{ 
    map<int, string> m ;
    m.insert(pair<int, string>(1, "abc")) ;
    m.insert(pair<int, string>(2, "def")) ;
    m.insert(pair<int, string>(3, "def")) ;
    m.insert(pair<int, string>(4, "ghi")) ;


    map<int, string>::iterator itor ;

    // 错误的写法
    for (itor = m.begin(); itor != m.end(); ++itor)
    {
        if (itor->second == "def")
        {
            m.erase(itor) ; // map是关联式容器,调用erase后,当前迭代器已经失效
        }
    }

    // 正确的写法
    for (itor = m.begin(); itor != m.end();)
    {
        if (itor->second == "def")
        {
            m.erase(itor++) ; // erase之后,令当前迭代器指向其后继。
        }
        else
        {
            ++itor;
        }
    }

    // 另一个正确的写法,利用erase的返回值,注意,有些版本的stl-map没有返回值,比如SGI版,但vc版的有
    for (itor = m.begin(); itor != m.end();)
    {
        if (itor->second == "def")
        {
            itor = m.erase(itor) ; // erase的返回值是指向被删除元素的后继元素的迭代器
        }
        else
        {
            ++itor;
        }
    }

    // Print m
    map<int, string>::const_iterator citor ;
    for (citor = m.begin(); citor != m.end(); ++citor)
    {
        cout << citor->first << ":" << citor->second << endl ;
    }

    getchar() ; 
    return 0 ; 
} 
复制代码

==

posted on   翰墨小生  阅读(12739)  评论(2编辑  收藏  举报

编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· [AI/GPT/综述] AI Agent的设计模式综述

导航

< 2010年7月 >
27 28 29 30 1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
1 2 3 4 5 6 7
书法字典:https://www.shufadict.com
点击右上角即可分享
微信分享提示