3. map的大小 在往map里面插入了数据,我们怎么知道当前已经插入了多少数据呢,可以用size函数,用法如下: Int nSize = mapStudent.size(); 4. 数据的遍历 这里也提供三种方法,对map进行遍历 第一种:应用前向迭代器,上面举例程序中到处都是了,略过不表 第二种:应用反相迭代器,下面举例说明,要体会效果,请自个动手运行程序 #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>::reverse_iterator iter; for(iter = mapStudent.rbegin(); iter != mapStudent.rend(); iter++) { Cout<<iter->first<<” ”<<iter->second<<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”)); int nSize = mapStudent.size() for(int nIndex = 0; nIndex < nSize; nIndex++) { Cout<<mapStudent[nIndex]<<end; } } 5. 数据的查找(包括判定这个关键字是否在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; } } |