map查找和统计

1.功能:对map容器进行数据查找和统计

2.函数原型

  • find(key); //查找key是否存在;若存在返回该键元素的迭代器;若不存在,返回set.end();
  • count(key); //统计key元素的个数
    #include<iostream>
    #include<map>
    using namespace std;
    
    void printmap(map<int, int>& m)
    {
    	for (map<int, int>::iterator it = m.begin(); it != m.end(); it++)
    	{
    		cout << "key=" << it->first << "  value=" << (*it).second << endl;
    	}
    	cout << endl;
    }
    
    void test1()
    {
    	map<int, int> m;
    	//插入
    	//第一种
    	m.insert(pair<int, int>(1, 10));
    	//第二种,优先推荐
    	m.insert(make_pair(3, 30));
    	//第三种
    	m.insert(map<int, int>::value_type(4, 40));
    	//第四种,[]方式不建议用于插入,但可以用于按照key来访问对应的value
    	m[5] = 50;
    	printmap(m);
    
    
    	//查找
    	map<int, int>::iterator pos = m.find(3);
    	
    	if (pos != m.end())
    	{
    		cout << "查找到了元素,其key=" << pos->first <<"  value="<<(*pos).second<< endl;
    	}
    	else
    	{
    		cout << "未找到!" << endl;
    	}
    
    	//统计
    	int num = m.count(3); //count结果要么为0要么为1,因为map容器中不允许有重复元素,后插的重复元素是无法插入成功的
    	//multimap的count可能大于1
    	cout << "num = " << num << endl;
    }
    int main()
    {
    	test1();
    	return 0;
    }

     

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值