简体   繁体   English

C++ unordered_set<insert function> 返回值</insert>

[英]C++ unordered_set<insert function> return value

I am trying to check return value of unordered_set's insert() function, but stuck with below error:我正在尝试检查 unordered_set 的 insert() function 的返回值,但遇到以下错误:

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错误-->从 'std::pair<std::__detail::_Node_iterator<int, true, false>, bool>' 转换为非标量类型 'std::unordered_set::iterator {aka std::__detail: :_Node_iterator<int, true, false>}' 请求

-->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. --> 如果插入 function 不成功,则插入 function 应该发送一个空迭代器,但是我无法为插入 ZC1C425268E68385D14AB5074C17A 的返回值声明正确的迭代器。 -->What should be the proper type of unordered_set iterator for insert function in this case? --> 在这种情况下,插入 function 的正确类型的 unordered_set 迭代器应该是什么?

Your understanding of the return value of unordered_set::insert is incorrect.您对 unordered_set::insert 返回值的理解是不正确的。

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 ) (来自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但实际上(假设你有 C++11)写起来要容易得多

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM