相关疑难解决方法(0)

为双向迭代器提供 operator+ 或 operator- 是否有任何缺点?

双向迭代器有没有像奢侈品随机访问迭代器,因此需要依赖于std::nextstd::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::nextstd::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

4
推荐指数
1
解决办法
121
查看次数