c – 什么容器类型提供比std :: map更好(平均)的性能?
发布时间:2020-12-16 10:16:39 所属栏目:百科 来源:网络整理
导读:在下面的示例中,std :: map结构填充了来自A – Z(对于键)的26个值和对于值的0 – 26. (在我的系统上)查找最后一个条目(10000000次)的时间对于向量大约为250毫秒,对于映射大约为125毫秒. (我使用发布模式编译,为g 4.4启用了O3选项) 但是,如果由于一些奇怪的原
在下面的示例中,std :: map结构填充了来自A – Z(对于键)的26个值和对于值的0 – 26. (在我的系统上)查找最后一个条目(10000000次)的时间对于向量大约为250毫秒,对于映射大约为125毫秒. (我使用发布模式编译,为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’; }
更通用的是,由于“密钥”是连续且密集的,因此使用数组(或向量)来保证Θ(1)访问时间. 如果您不需要对密钥进行排序,则use (有时,特别是对于小数据集,线性搜索比哈希表(unordered_map)/平衡二叉树(map)更快,因为前者具有更简单的算法,因此减少了big-O中的隐藏常量.轮廓.) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |