Error C2676: std::set::const_iterator doesn't have operator+ function?

断了今生、忘了曾经 提交于 2021-02-10 20:09:42

问题


std::set<int> s = { 1,2,3,4,5 };
std::set<int> s2(s.begin(), s.begin() + 2);

I want to assgin several values of s into s2. But got below compile error:

Error C2676 binary '+': 'std::_Tree_const_iterator<std::_Tree_val<std::_Tree_simple_types<_Ty>>>' does not define this operator or a conversion to a type acceptable to the predefined

It seems std::set::const_iterator doesn't have operator+ method.


回答1:


It seems std::set::const_iterator doesn't have operator+ method.

You are right about this.

Operations such as s.begin() + 2 is only possible for random access iterators (see the Expression s in the link). But, std::set has only bidirectional iterator (both std::set::iterator and std::set::const_iterator).


However, you could use std::next to do this job in a generic way, which returns the nth successor of iterator which we pass.

#include <iterator>  // std::next

std::set<int> s2(s.begin(), std::next(s.begin(), 2));
// or const_iterator    
std::set<int> s3(s.cbegin(), std::next(s.cbegin(), 2));



回答2:


sets are usually implemented as a tree rather than a contiguous data store. With a tree you can only find a contained item from the proceeding item and have to iterate one at a time, making the + operator not very effective. As a result they only provide Bi-Directional Iterators.

To get an effective operator+ you need a container that can provide Random Access Iterators



来源:https://stackoverflow.com/questions/59572855/error-c2676-stdsetconst-iterator-doesnt-have-operator-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!