什么容器类型提供比std :: map更好(平均)的性能?

Tru*_*eon 3 c++ performance map

在下面的示例中,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;
}
Run Code Online (Sandbox Code Playgroud)

ken*_*ytm 8

对于您的示例,请使用 int value(char x) { return x - 'a'; }

更通用的是,由于"密钥"是连续且密集的,因此使用数组(或向量)来保证Θ(1)访问时间.

如果您不需要对键进行排序,请使用unordered_map,这应该为大多数操作提供摊销的对数改进(即O(log n) - > O(1)).

(有时,特别是对于小数据集,线性搜索比哈希表(unordered_map)/平衡二叉树(map)更快,因为前者具有更简单的算法,因此减少了big-O中的隐藏常量.轮廓.)