C++的map与multimap的使用

map 键-值对的集合,可理解为关联数组。

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

int main(){
    map<string, int> word_cnt;
    string word;
    /*利用数组下标插入
    while(cin >> word){
        ++word_cnt[word];
    }
    */

    /*利用insert插入*/
    while(cin >> word){
        pair<map<string, int>::iterator, int> ret = word_cnt.insert(make_pair(word, 1));
        if(!ret.second)
            ++ret.first->second;
    }

    /*erase删除键为June的元素*/
    word_cnt.erase("June");

    /*迭代遍历*/
    map<string, int>::const_iterator it = word_cnt.begin();
    while(it != word_cnt.end()){
        cout << it->first << " occurs "
             << it->second << " times" << endl;
        ++it;
    }

    /*测试数据:June July the on the table the July book*/

    /*查找 find count*/
    map<string, int>::iterator u = word_cnt.find("the");
    //find返回迭代器,若不存在则返回指向末端的迭代器
    if(u != word_cnt.end()){
        cout << u->first << " occurs "
             << u->second << " times" << endl;
    }

    int cnt = word_cnt.count("July");
    //count的返回值是0(容器中不存在)或1(容器中存在),因为map是一个键对应一个值
    cout << cnt << endl;

}

multimap 一个键可对应多个值,不能使用下标操作。

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

int main(){

    multimap<string, string> author;
    /*用insert添加元素*/
    author.insert(make_pair(string("Happy"), string("Hello")));
    author.insert(make_pair(string("June"), string("July")));
    author.insert(make_pair(string("Happy"), string("Hi")));
    author.insert(make_pair(string("Happy"), string("Good")));

    /*count(k)返回容器中有k键的元素个数*/
    multimap<string, string>::size_type cnt = author.count("Happy");
    cout << cnt << endl;

    /*find(k)函数返回迭代器*/
    multimap<string, string>::iterator c = author.find("Happy");
    typedef multimap<string, string>::size_type sz_type;
    for(sz_type i = 0; i != cnt; ++i, ++c)
        cout << c->second << " ";

    /*lower_bound(k)返回不小于k的迭代器,lower_bound(k)返回大于k的迭代器。*/
    cout << endl << author.lower_bound("Happy")->second << " "
         << author.upper_bound("Happy")->second << endl;

    /*equal_range(k)返回存在k键的元素范围的pair类型(左闭右开区间)*/
    typedef multimap<string, string>::iterator authors;
    pair<authors, authors> k = author.equal_range("Happy");
    cout << k.first->second << " "
         << k.second->second << endl;


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值