最近工作中需要用到标准模板库的容器, 按输入的值在容器上查找到对应的位置,然后输出该位置后的在考虑是选用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的顺序输出. 实现了我要的功能.