4.map查找和统计

#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;
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容