在双向迭代器有没有像奢侈品随机访问迭代器,因此需要依赖于std::next和std::prev,当有人需要做的操作,如
std::set<int> s{ 1, 2, 3, 4, 5 };
//std::set<int> s2(s.cbegin(), s.cbegin() + 2); // won't work as there is no operator+ for std::set::const_iterator
std::set<int> s2(s.cbegin(), std::next(s.cbegin(), 2));
//std::set<int> s3(s.cbegin(), s.cend() - 2); // won't work as there is no operator- for std::set::const_iterator
std::set<int> s3(s.cbegin(), std::prev(s.cend(), 2));
Run Code Online (Sandbox Code Playgroud)
但是,我们可以实现这些 operator+并operator-使用上面的std::next和std::prev.
#include <set>
#include <iterator> // std::iterator_traits, std::next, std::prev
template<typename InputIt>
constexpr InputIt operator+(InputIt it,
typename …Run Code Online (Sandbox Code Playgroud) c++ iterator operator-overloading c++-standard-library language-lawyer