如何更有效地插入到std::map中

how i insert into std::map more efficiently

本文关键字:map std 何更 有效地 插入      更新时间:2023-10-16

我有类似这样的代码:

struct Record{
     std::string key;
     // ...
};
void push_record(Record &out, std::map<std::string, int> &vmap){
    const auto &it = vmap.find(out.key);
    long pos;
    if (it != vmap.end()){
        pos = it->second;
    }else{
        pos = calculate_pos(out);
        vmap.insert( Record(std::move(out.key), pos) ); // here move
    }
    // use pos
}

如何使代码更高效?

目前,代码不是很有效,因为它查找到map两次。第一次是检查值,第二次是插入

我也想使用std::move(out.key),这就是为什么我没有使用vmap[out.key]之类的东西。

我看到你可以把建议传递给insert,但我找不到好的例子。

std::map有一个方法upper_bound,您可以使用它来查找大于的第一个元素:

const auto it = vmap.upper_bound(out.key);

由于映射不能包含重复的键,并且这是第一个较大的元素,因此具有给定键的值只能位于前一个迭代器位置,或者根本不在映射中:

// Begin iterator means it definitely isn't in map
if(vmap.empty() || it == vmap.begin()) {
    // Perform insert...
} else {
    if((--it)->first != out.key)) {
        // Doesn't exist, perform insert with hint.
        // Note it will be inserted just prior to this (C++11).
        vmap.insert(++it, ...);
    } else {
      // It's in the map, do stuff with it
    }
}

正如其他人所说,这可能充其量只是一个微优化。这也使代码更难看,更难阅读,所以我强烈建议在使用这样的东西之前进行分析。

相关文章: