当向map容器中插入数据,用迭代器输出是会按顺序输出
如下:
#include <iostream> #include <string> #include <map> using namespace std; typedef pair <string, string> Str_Pair; int main(void) { map<string,string> mymap; typedef map<string,string>::iterator CIR; mymap.insert(Str_Pair("abcd"," 唐伯虎点秋香" )); mymap.insert(Str_Pair("ab"," 唐伯虎点秋香" )); mymap.insert(Str_Pair("abc"," 唐伯虎点秋香" )); mymap.insert(Str_Pair("a"," 唐伯虎点秋香" )); for(CIR npos=mymap.begin(); npos!=mymap.end();npos++) { cout<<npos->first<<" "<<npos->second<<endl; } return 0; } |
输出结果为: a 唐伯虎点秋香 ab 唐伯虎点秋香 abc 唐伯虎点秋香 abcd 唐伯虎点秋香 |
但是有的时候我们不要求输出有序,即按照插入的顺序输出
下面用vector容器模拟这种情况(对于查找这种方法速度没有map快)
#include <iostream> #include <string> #include <vector> using namespace std; typedef pair <string, string> Str_Pair; int main(void) { vector<Str_Pair> mymap; typedef vector<Str_Pair>::iterator CIR; mymap.push_back(Str_Pair("abcd"," 唐伯虎点秋香" )); mymap.push_back(Str_Pair("ab"," 唐伯虎点秋香" )); mymap.push_back(Str_Pair("abc"," 唐伯虎点秋香" )); mymap.push_back(Str_Pair("a"," 唐伯虎点秋香" )); for(CIR npos=mymap.begin(); npos!=mymap.end();npos++) { cout<<npos->first<<" "<<npos->second<<endl; } return 0; } |
输出结果为: abcd 唐伯虎点秋香 ab 唐伯虎点秋香 abc 唐伯虎点秋香 a 唐伯虎点秋香 |