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; }