跟踪节点遍历调用 std::map::find



我正在对 std::map 执行大量查找、插入和删除。我正在考虑添加一些代码来优化速度,但我想收集一些有关当前工作负载的统计信息。具体来说,我想跟踪每次调用时"查找"必须遍历多少节点,以便我可以保持运行计数。

我在想,如果我的地图中的大多数更改都发生在前面,我最好在使用"查找"使用的树之前搜索前 N 个条目。

Find 必须使用映射的比较函数比较元素,因此您可以提供一个自定义比较函数来计算它被调用的次数,以查看它在每次调用中做了多少工作(基本上是遍历了多少节点)。

不过,在这种情况下,我不明白在调用 find() 之前搜索前 N 个条目会有什么帮助。遍历映射中的条目只是按排序顺序遍历树,因此它不会比仅调用 find() 更有效,除非你的比较函数以某种方式比检查相等性昂贵得多。

示例代码:

#include <algorithm>
#include <iostream>
#include <map>
#include <numeric>
#include <vector>
using namespace std;
int main() {
    vector<int> v(100);
    iota(begin(v), end(v), 0);
    vector<pair<int, int>> vp(v.size());
    transform(begin(v), end(v), begin(vp), [](int i) { return make_pair(i, i); });
    int compareCount = 0;
    auto countingCompare = [&](int x, int y) { ++compareCount; return x < y; };
    map<int, int, decltype(countingCompare)> m(begin(vp), end(vp), countingCompare);
    cout << "Compares during construction: " << compareCount << "n";
    compareCount = 0;
    auto pos = m.find(50);
    cout << "Compares during find(): " << compareCount << "n";
}

如果这对您的键/值结构可行,则值得考虑unordered_map(在 C++11 或 TR1 中)作为替代方案。 std::map ,作为一个平衡的树,在这种使用配置文件下不太可能表现良好,而搜索前 N 个的混合方法对我来说似乎是很多工作,没有保证的回报。

最新更新