美文网首页
4.map查找和统计

4.map查找和统计

作者: lxr_ | 来源:发表于2021-04-24 10:01 被阅读0次
#include<iostream>
using namespace std;

#include<map>

//find(key);查找key是否存在,返回该键的元素的迭代器,若不存在,返回set.end()
//count(key);统计key的元素个数


void test0401()
{
    map<int, int> m;

    m.insert(make_pair(1, 10));
    m.insert(make_pair(2, 20));
    m.insert(make_pair(3, 30));
    m.insert(make_pair(4, 40));
    m.insert(make_pair(3, 30));//插不进去

    map<int,int>::iterator pos=m.find(5);
    if (pos != m.end())
    {
        cout << "找到了" << "value=" << pos->second << endl;
    }
    else
    {
        cout << "未找到" << endl;
    }

    //map容器元素个数要么为0要么为1
    int num = m.count(3);

    cout << "key=3的个数:" << num << endl;

    //multimap中的元素个数可能会大于1,因为他允许重复的元素存在
    multimap<int, int> m1;
    m1.insert(make_pair(1, 19));
    m1.insert(make_pair(2, 19));
    m1.insert(make_pair(1, 4));
    m1.insert(make_pair(1, 1));

    cout << "key为1的个数:" << m1.count(1) << endl;
    for (multimap<int, int>::iterator it = m1.begin(); it != m1.end(); it++)
    {
        cout << "key=" << it->first << "\t" << "value=" << it->second << endl;
    }
}

int main()
{

    test0401();

    system("pause");
    return 0;
}

相关文章

网友评论

      本文标题:4.map查找和统计

      本文链接:https://www.haomeiwen.com/subject/txmxrltx.html