xml*_*lmx 3 c++ performance standards c++11 c++17
#include <set>
#include <vector>
using Value = std::vector<int>;
int main()
{
auto coll = std::set<Value>{};
// ......
// Insert many values here.
// ......
auto new_value = Value{1, 2, 3};
auto const pos = coll.find(new_value);
if (pos != coll.end())
{
// Good
coll.emplace_hint(coll.erase(pos), std::move(new_value));
}
else
{
// Performance penalty!
// No hint here, though coll.find(new_value) knows that.
coll.emplace(std::move(new_value));
}
}
Run Code Online (Sandbox Code Playgroud)
为什么不 std::set::find
提供提示迭代器?
的结果std::set::lower_bound()
可用作 的提示emplace_hint()
。因此,只需使用lower_bound()
代替find()
,并检查返回的键是否与lower_bound()
您要查找的内容匹配,而不是检查返回的迭代器是否find()
为end()
。