问题
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 haveoperator+
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 n
th 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:
set
s 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