不支持随机访问迭代器,只能从容器中第一个元素或最后一个元素开始遍历容器,直到找到该位置。
size_type map.count(keyElem); //返回容器中key为keyElem的对组个数。对map来说,要么是0,要么是1。对multimap来说,值可能大于1。
int count= mapStu.count(4);bool empty() const;判断容器中是否有元素,若无元素,则返回 true;反之,返回 false。
程序一:
#include <iostream> #include<map> using namespace std; int main() { map<int, string> mapStu; mapStu.insert(pair<int, string>(3, "张3")); mapStu.insert(map<int, string>::value_type(1, "小李")); mapStu[4] = "小四"; mapStu.at(4) = "小王"; mapStu[5] = "小五"; map<int, string>::iterator it; it=mapStu.find(4); int count; count = mapStu.count(4); mapStu.erase(++it); mapStu.erase(4); it = mapStu.begin(); map<int, string>::iterator it_last = mapStu.end(); mapStu.erase(it,--it_last); mapStu.clear(); return 0; }程序二:
#include <iostream> #include<map> using namespace std; int main() { //保存学生学号和姓名 map<int,string> s; for (int i = 0; i < 10; i++) { string ch = "ABCDEFGHIJ"; string name= "maye"; //注意pair的类型参数,需要和map的一致 s.insert(pair<int,string>(i,name+ch[i])); } s.insert(make_pair(111, "C语言PLUS")); s.insert(map<int, string>::value_type(222, "法外狂徒")); s[333] = "顽石"; cout << "学号:" <<" "<< "姓名:" << endl; for (map<int, string>::iterator it = s.begin(); it != s.end(); it++) { cout << it->first << " " << it->second << endl; } //cout << "\nmap size():" << s.size() << endl; //查找指定的key值,返回指向的迭代器,没有找到返回end()迭代器,所以再输出之前需要判断是否找到 map<int, string>::iterator it1 = s.find(6); if (it1 != s.end()) { cout << it1->first << " " << it1->second << endl; } //如果map中有等于4的key,则返回指向4的迭代器,如果没有返回第一个大于4的元素的迭代器,没有找到返回end()迭代器 it1 = s.lower_bound(4); if (it1 != s.end()) { cout << it1->first << " " << it1->second << endl; } //如果map中有大于4的key,返回第一个大于4的元素的迭代器,没有找到返回end()迭代器 it1 = s.upper_bound(4); if (it1 != s.end()) { cout << it1->first << " " << it1->second << endl; } cout << "------------------我是 C语言Plus 华丽分割线" << endl; //定义对组,接受equal_range()的返回值 pair<map<int, string>::iterator, map<int, string>::iterator> pa; //如果没有找到会返回end() pa = s.equal_range(7); if (it1 != s.end()) { cout << pa.first->first << " " << pa.first->second << endl; cout << pa.second->first << " " << pa.second->second << endl; } s.clear();//清空 cout << s.size() << endl; return 0; }文章参考或转自:https://mp.weixin.qq.com/s/gqeYUhjYorKei13t3Q4Hsg