C++ map基本操作实例

C++ STL的map是一个基于红黑树的容器类,查找和删除的效率都是O(logn),这是一个通过空间消耗获得时间效率的典型模式。通过具体的例子来看下这个容器类的插入,删除和查询操作。

#include<iostream>
#include<map>
#include<string>
using namespace std;

void mapExample()
{
    /*插入操作*/
    map<int, string> mapTest;   //声明一个名为mapTest的map容器对象

    mapTest.insert(pair<int, string>(1, "world"));
    mapTest.insert(pair<int, string>(2, "peace"));  //map插入操作

    mapTest[0] = "My wish is";                        //以数组的方式插入元素

    map<int, string>::iterator ite;                      //声明一个map<int,string>的内容迭代器
    for (ite = mapTest.begin(); ite != mapTest.end(); ite++)   //map遍历
    {
        cout << ite->first << "," << ite->second << endl;
    }
    /*我们测试一下第二次插入相同的key值,是否能插入成功*/
    pair<map<int, string>::iterator, bool> result;
    result = mapTest.insert(pair<int, string>(1, "I am a chengXuYuan"));
    cout << "the result is: " << result.second << endl;  //为0则表示失败,为1则表示成功

    /*删除操作*/
    int n = mapTest.erase(1);//删除key=1的元素
    cout << n << endl;
    for (ite = mapTest.begin(); ite != mapTest.end(); ite++)
    {
        cout << ite->first << "," << ite->second << endl;
    }

}


int main()
{
    mapExample();

    return 0;
}

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值