标准模板库map, vector查找用法

      最近工作中需要用到标准模板库的容器, 按输入的值在容器上查找到对应的位置,然后输出该位置后的在考虑是选用map还是vector的时候, 经过测试我最终选定用vector容器.

原因如下:

用map容器我需要用string作为主键进行快速查找.我用如下代码测试:

typedef std::map<string, int> FileMap;
FileMap::iterator iter;
int i = 0;

FileMap m_filemap;

char szKey[20] = {0};

while ( i < 10000 )
{
    sprintf(szKey, "Key %d", i); 
    m_filemap.insert(FileMap::value_type(szKey, i));
    i++
}

iter = m_filemap.find("Key 5000");
for ( ; iter != m_filemap.end(); ++iter )
{
 cout << iter.first << "---" << iter.second << endl;
}

发现输出的的顺序都乱了, 不是和insert 的顺序一样. 理想状态应该输出为Key 5000 ---5000... Key 9999---9999.

分析得出应该是map以string作为主键存放的顺序和map以int作为主键存放的顺序不同(以int为主键时能够按理想状态输出).因此如果选用map达不到我的要求.

用vector容器

typedef std::vector<string> FileVector;
FileVector::iterator iter;
FileVector m_filevector;
int i = 0;
while ( i < 10000 )
{
    sprintf(szKey, "Key %d", i); 
    m_filevector.push_back(szKey);
    i++
}

iter = find(m_filevector.begin(), m_filevector.end(), "Key 5000");
for ( ; iter != m_filemap.end(); ++iter )
{
    cout << iter.first << "---" << iter.second << endl;
}

能够根据给定的值快速的查找到指定位置, 然后从指定位置根据push_back的顺序输出. 实现了我要的功能.

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值