Search code examples
c++iteratoroperator-overloadingstdstdset

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.


Solution

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