Zhang
Zhang

Reputation: 3356

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

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.

Upvotes: 1

Views: 580

Answers (2)

JeJo
JeJo

Reputation: 33092

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));

Upvotes: 3

user4581301
user4581301

Reputation: 33982

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

Upvotes: 2

Related Questions