multimap的用法示例

本示例代码演示了multimap的构造、插入、遍历、2种查询方法、统计某个key存在的个数等功能。
更多的演示示例代码,请见 《C++标准程序库》,侯捷/孟岩 译

#pragma warning(disable:4786)
#include <map>
#include <iostream>
#include <string>
#include <UTILITY>
using namespace std;

struct userdevice
{
    string m_devicename;
    long m_deviced;
    int m_devicePopedom;
};

typedef multimap<string, userdevice> USERTABLE;        
typedef USERTABLE::const_iterator CIT;
typedef pair<CIT, CIT> Range;

int main(int argc, char* argv[])
{

    /* 由于键值允许重复插入,在 multimap 容器中具有同一个键值的元素有可能不只一个。 因此,multimap 容器的 find 函数将返回第一个搜索到的元素位置,如果元素不存在,则返回 end 结束元素位置。 equal_range 函数则返回一个可指示相等元素范围区间的 pair 对象。 */
    if (1)
    {
        // 定义一个迭代器
        CIT it;
        // 定义4个设备
        userdevice d1, d2, d3, d4;
        d1.m_deviced = 12341234;
        d1.m_devicename = "d1";
        d1.m_devicePopedom = 123;

        d2.m_deviced = 23622344;
        d2.m_devicename = "d2";
        d2.m_devicePopedom = 234;

        d3.m_deviced = 3451234;
        d3.m_devicename = "d3";
        d3.m_devicePopedom = 345;

        d4.m_deviced = 43622344;
        d4.m_devicename = "d4";
        d4.m_devicePopedom = 456;

        // 插入
        USERTABLE m_user;
        m_user.insert(pair<string, userdevice>("zhangsanfeng",d1));
        m_user.insert(pair<string, userdevice>("zhangsanfeng",d2));

        m_user.insert(pair<string, userdevice>("zhangsanfeng2",d3));
        m_user.insert(pair<string, userdevice>("zhangsanfeng2",d4));

        // 遍历
        CIT it3 = m_user.begin();
        while (it3!=m_user.end())
        {
            cout<< it3->second.m_deviced <<","
                << it3->second.m_devicename.c_str()<<","
                << it3->second.m_devicePopedom
                << endl;

            ++it3;
        }
        cout<< endl;

        // 查找方法一(查找key值是"zhangsanfeng")
        Range range = m_user.equal_range("zhangsanfeng");
        for (CIT i = range.first; i!=range.second; ++i)
        {
            cout<< i->second.m_deviced <<","
                << i->second.m_devicename.c_str()<<","
                << i->second.m_devicePopedom
                << endl;
        }
        cout<< endl;



        // 查找方法二(查找key值是"zhangsanfeng2")
        CIT it2 = m_user.find("zhangsanfeng2");
        while(it2!=m_user.end())
        {        
            cout<< it2->second.m_deviced <<","
                << it2->second.m_devicename.c_str()<<","
                << it2->second.m_devicePopedom
                << endl;
            ++it2;
        }
        cout<< endl;

        cout<<"count & size"<<endl;
        // 打印键值为 3 的元素个数
        cout << m_user.count("zhangsanfeng2") << endl;
        // 打印元素个数
        cout << m_user.size() << endl;
    }
    getchar();
    return 0;
}

你可能感兴趣的:(Multimap)