在以下示例中,std::map 结构填充了 A - Z(键)和 0 - 26 中的 26 个值。 (在我的系统上)查找最后一个条目(10000000 次)所花费的时间对于 vector 大约是 250 毫秒,对于 map 大约是 125 毫秒。 (我使用 Release模式编译,为 g++ 4.4 打开了 O3 选项)
但是如果出于某种奇怪的原因我想要比 std::map 更好的性能,我需要考虑使用哪些数据结构和函数?
如果答案对您来说显而易见,我深表歉意,但我在 C++ 编程的性能关键方面没有太多经验。
#include <ctime>
#include <map>
#include <vector>
#include <iostream>
struct mystruct
{
char key;
int value;
mystruct(char k = 0, int v = 0) : key(k), value(v) { }
};
int find(const std::vector<mystruct>& ref, char key)
{
for (std::vector<mystruct>::const_iterator i = ref.begin(); i != ref.end(); ++i)
if (i->key == key) return i->value;
return -1;
}
int main()
{
std::map<char, int> mymap;
std::vector<mystruct> myvec;
for (int i = 'a'; i < 'a' + 26; ++i)
{
mymap[i] = i - 'a';
myvec.push_back(mystruct(i, i - 'a'));
}
int pre = clock();
for (int i = 0; i < 10000000; ++i)
{
find(myvec, 'z');
}
std::cout << "linear scan: milli " << clock() - pre << "\n";
pre = clock();
for (int i = 0; i < 10000000; ++i)
{
mymap['z'];
}
std::cout << "map scan: milli " << clock() - pre << "\n";
return 0;
}
最佳答案
对于您的示例,使用 int value(char x) { return x - 'a'; }
更一般化,由于“键”是连续且密集的,使用数组(或 vector )来保证 Θ(1) 访问时间。
如果不需要对键进行排序,use unordered_map
,这应该为大多数操作提供摊销的对数改进(即 O(log n) -> O(1))。
(有时,尤其是对于小数据集,线性搜索比哈希表(unordered_map)/平衡二叉树(map)更快,因为前者的算法简单得多,从而减少了big-O中的隐藏常量。简介, 配置文件, 配置文件。)
关于c++ - 哪种容器类型提供比 std::map 更好的(平均)性能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2568996/