在unordered_set中插入一个新元素:提示应该是end()吗?

Lor*_*one 5 c++ stl c++11

如果我确定某个值还没有进入unordered_set,并且我要插入这样的值,那么将此set end()迭代器作为提示传递是否正确?

编辑:

码:

#include <unordered_set>
using namespace std;

unordered_set<int> someset;

int main(){
    auto it=someset.find(0);
    if(it==someset.end()) someset.insert(it, 0);    //correct? possible performance boost if the set is actually populated?
}
Run Code Online (Sandbox Code Playgroud)

Naw*_*waz 8

我想,你可以简单地调用insert函数,返回的值将告诉你是否插入了值,或者它是否已经存在于集合中.

auto p = someset.insert(value);
if (!p.second) 
{
   std::cout << "value was already present in the set" << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

实际上p是类型std::pair<iterator,bool>,因此p.second告诉您是否插入了值,或者它是否已经存在于集合中,并且p.first是迭代器,它告诉您值的位置.

请记住,这比您的方法更快,因为我的解决方案减少了整体工作.