1
votes

I am trying to check return value of unordered_set's insert() function, but stuck with below error:

unordered_set<int> t;
t.insert(1);
t.insert(2);
t.insert(3);
t.insert(4);
std::unordered_set<int>::iterator it = t.insert(1); **//Error**
cout<<"size of t="<<t.size()<<endl;

Error-->conversion from 'std::pair<std::__detail::_Node_iterator<int, true, false>, bool>' to non-scalar type 'std::unordered_set::iterator {aka std::__detail::_Node_iterator<int, true, false>}' requested

-->Insert function should send a empty iterator if the insert function is not successful, but I am unable to declare the proper iterator for return value of insert function. -->What should be the proper type of unordered_set iterator for insert function in this case?

1
See std::unordered_set::insert, the return is not an iterator, but apair<iterator, bool>.Olaf Dietsche
have you checked with auto ? auto does the type deduction in most compile time typesSushant Choudhary

1 Answers

2
votes

Your understanding of the return value of unordered_set::insert is incorrect.

Returns a pair consisting of an iterator to the inserted element (or to the element that prevented the insertion) and a bool denoting whether the insertion took place.

(from cppreference)

So the correct declaration is

std::pair<std::unordered_set<int>::iterator, bool> it = t.insert(1);

but really (assuming you have C++11) it's a lot easier to write

auto it = t.insert(1);

If you are only interested in the returned iterator, then you could also write

std::unordered_set<int>::iterator it = t.insert(1).first;

or again using auto

auto it = t.insert(1).first;