C++primer第4版第十章关联容器

Talk is cheap, show me the code.

  1. 使用pair对象必须包含头文件utility,创建pair对象有多中方式:

    pair<string, int> p;
    p.first = "hello";
    p.second = 12;
    pair<string, int> p1("hello", 12);
    pair<string, int> p2 = make_pair("hello", 12);

  2. 使用map对象必须包含头文件map,而且作为key的类型必须定义了 < 运算操作;

  3. 不能使用map的下标操作来判断一个key是否存在于map中,而应当用find或者count函数来判断,因为下标操作即使元素不存在也会创建一个元素,并置为初始值。优先选择find函数来查找。

    map<string, int> map1;
    map<string, int>::iterator it = map1.find("hello"); //找到就返回该元素的迭代器,没找到就返回map1.end()迭代器
    int count = map1.count("hello"); //对于map来说只能返回0 或者 1

  4. map的常用操作有:insert(key),map[key]=value,erase(key),find(key),count(key)等等。

  5. 使用set对象必须包含头文件set,set中的元素类型都是const,不能修改,而且都不重复。set常用操作有:insert(key),erase(key),find(key),count(key)等等。

  6. set头文件中还有multiset,map头文件中还有multimap,都支持多个相同key的元素,这些相同key的元素都相邻存放。需要访问时提供了起始和终止下一位置的迭代器,这时候count()函数就体现出它的意义。

    multiset<string> ms;
    ms.insert("hello");
    ms.insert("hello");
    multiset<string>::iterator beg = ms.lower_bound("hello");
    multiset<string>::iterator end = ms.upper_bound("hello");
    while (beg != end)
    {
    cout << *beg++ << endl;
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值