C++ map multimap

map multimap

map,multimap key-value对容器,也叫字典,map中不能存放key相同的元素,而multimap可以,容器中元素默认按升序排序

map multimap的相关操作

m.insert(map<T1,T2>::value_type(a1,a2));
m.insert(make_pair(a1,a2));
m.insert(pair<T1,T2>(a1,a2));
a[a1]=a2;                                //multimap不能用这种方式
m.find(val)              //查找元素,返回迭代器
m.erase(key)             //通过key删除元素
m.erase(it)              //通过迭代器删除元素
m.erase(it1,it2)         //删除迭代器范围内的元素

学习代码


#include <iostream>
#include <map>
#include <string>

using namespace std;

int main()
{
    map<int, string> a;  //键不能重复,默认按升序排序
    multimap<int, string> ma;
    a.insert(map<int, string>::value_type(1, "One"));
    a.insert(map<int, string>::value_type(1, "one"));
    a.insert(map<int, string>::value_type(2, "Two"));
    a.insert(map<int, string>::value_type(3, "Three"));
    a.insert(make_pair(-1, "Minus One"));
    a.insert(pair<int, string>(1000, "One Thousand"));
    a[1000000] = "One Million";//multimap不能用这种方式

    cout << "最简单那的查找" << endl;
    cout << a[3] << endl;

    cout << "map里一共有" << a.size() << "个kye-value对数据" << endl;
    map<int, string>::const_iterator it = a.begin();
    while (it != a.end())
    {
        cout << "key" << it->first ;
        cout << " value" << it->second.c_str();
        cout << endl;
        ++it;

    }

    ma.insert(multimap<int, string>::value_type(3, "Three"));
    ma.insert(multimap<int, string>::value_type(45, "Forty Five"));
    ma.insert(make_pair(-1, "Minus one"));
    ma.insert(pair<int, string>(1000, "One Thousand"));
    ma.insert(pair<int, string>(1000, "One Thousand"));

    multimap<int, string>::const_iterator itm = ma.begin();
    while (itm != ma.end())
    {
        cout << "key:" << itm->first;
        cout << " value:" << itm->second.c_str();
        cout << endl;
        ++itm;
    }
    cout << "multimap里有" << ma.count(1000) << "个1000" << endl;

    multimap<int, string>::const_iterator fi;
    fi=ma.find(45);
    if (fi != ma.end())
    {
        cout << "找到了" << fi->first<<"  "<<fi->second.c_str()<< endl;
    }
    else
    {
        cout << "没找到" << endl;
    }

    fi = ma.find(1000);
    if (fi != ma.end())
    {
        cout << "找到了1000" << endl;
        size_t n = ma.count(1000);
        for (size_t i = 0; i < n; i++)
        {
            cout << "key:" << fi->first << "value:" << fi->second.c_str() << endl;
            ++fi;
        }
    }
    else {
        cout << "没找到" << endl;
    }

    if (ma.erase(-1) > 0)
        cout << "删除-1成功" << endl;

    multimap<int, string>::iterator itm2 = ma.find(45);
    if (itm2 != ma.end())
    {
        ma.erase(itm2);
        cout << "删除45成功" << endl;
    }

    ma.erase(ma.lower_bound(1000), ma.upper_bound(1000));//迭代器

    getchar();
    return 0;

}
上一篇:C#逻辑运算符详解


下一篇:Jmeter:相应断言介绍