4
、 数据的查找(包括判定这个关键字是否在map中出现)
在这里我们将体会,map在数据插入时保证有序的好处。
要判定一个数据(关键字)是否在map中出现的方法比较多,这里标题虽然是数据的查找,在这里将穿插着大量的map基本用法。
这里给出三种数据查找方法
第一种:用count函数来判定关键字是否出现,其缺点是无法定位数据出现位置,由于map的特性,一对一的映射关系,就决定了count函数的返回值只有两个,要么是0,要么是1,出现的情况,当然是返回1了
第二种:用find函数来定位数据出现位置,它返回的一个迭代器,当数据出现时,它返回数据所在位置的迭代器,如果map中没有要查找的数据,它返回的迭代器等于end函数返回的迭代器。
#include <map> #include <string> #include <iostream> using namespace std; int main() { map<int, string> mapStudent; mapStudent.insert(pair<int, string>(1, "student_one")); mapStudent.insert(pair<int, string>(2, "student_two")); mapStudent.insert(pair<int, string>(3, "student_three")); map<int, string>::iterator iter; iter = mapStudent.find(1); if(iter != mapStudent.end()) { cout<<"Find, the value is "<<iter->second<<endl; } else { cout<<"Do not Find"<<endl; } iter = mapStudent.find(6); if(iter != mapStudent.end()) { cout<<"Find, the value is "<<iter->second<<endl; } else { cout<<"Do not Find"<<endl; } } /*********************************** Find, the value is student_one Do not Find Process returned 0 (0x0) execution time : 1.030 s Press any key to continue. *************************************/
5、 数据的清空与判空
清空map中的数据可以用clear()函数,判定map中是否有数据可以用empty()函数,它返回true则说明是空map
6. 数据的删除
这里要用到erase函数,它有三个重载了的函数,下面在例子中详细说明它们的用法
#include <map> #include <string> #include <iostream> using namespace std; int main() { map<int, string> mapStudent; mapStudent.insert(pair<int, string>(1, "student_one")); mapStudent.insert(pair<int, string>(2, "student_two")); mapStudent.insert(pair<int, string>(3, "student_three")); map<int, string>::iterator iter; cout<<"--------------------no erase--------------------"<<endl; for(iter = mapStudent.begin(); iter != mapStudent.end(); iter++) { cout<<iter->first<<" "<<iter->second<<endl; } cout<<"-------------erase (iter)--------iter = mapStudent.find(1)--"<<endl; iter = mapStudent.find(1); mapStudent.erase(iter); //如果要删除1,用关键字删除 for(iter = mapStudent.begin(); iter != mapStudent.end(); iter++) { cout<<iter->first<<" "<<iter->second<<endl; } cout<<"-------------int n = mapStudent.erase(2)----"<<endl; int n = mapStudent.erase(2);//如果删除了会返回1,否则返回0 for(iter = mapStudent.begin(); iter != mapStudent.end(); iter++) { cout<<iter->first<<" "<<iter->second<<endl; } cout<<"--- mapStudent.erase(mapStudent.begin(), mapStudent.end())-----"<<endl; //一下代码把整个map清空 mapStudent.erase(mapStudent.begin(), mapStudent.end()); for(iter = mapStudent.begin(); iter != mapStudent.end(); iter++) { cout<<iter->first<<" "<<iter->second<<endl; } } /************************** --------------------no erase-------------------- 1 student_one 2 student_two 3 student_three -------------erase (iter)--------iter = mapStudent.find(1)-- 2 student_two 3 student_three -------------int n = mapStudent.erase(2)---- 3 student_three --- mapStudent.erase(mapStudent.begin(), mapStudent.end())----- Process returned 0 (0x0) execution time : 1.513 s Press any key to continue. ****************************/