map与vector

当向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   唐伯虎点秋香

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值