为什么我不能在列表迭代器上使用 += 运算符?

Why can't I use += operator on a list iterator?

我有一个来自 std::list<std::string> 的迭代器,但是当我尝试使用 += 推进它时,出现编译错误。

密码是:

#include <list>
#include <iostream>
#include <string>
int main() {
    std::list<std::string> x;

    x.push_front("British");
    x.push_back("character");
    x.push_front("Coding is unco");
    x.push_back("Society");
    x.push_back("City Hole");
    auto iter = x.begin();
    iter += 3;
    //std::advance(iter, 3);
    x.erase(iter);

    for (auto &e: x) {
        std::cout << e << "\n";
    }
}

如果我使用 clang++ -std=c++11 -o li li.cpp 编译它,我得到:

li.cpp:13:10: error: no viable overloaded '+='
    iter += 3;
    ~~~~ ^  ~
1 error generated.

为什么我不能将 += 与此迭代器一起使用?

std::list is BidirectionalIterator, which doesn't support operator+= like RandomAccessIterator 的迭代器。

你可以使用operator++InputIterator支持(包括BidirectionalIterator),比如

++iter;
++iter;
++iter;

但是很丑。最好的方法是如您评论的那样,使用 std::advance (或 std::next (C++11 起))代替,可以与 InputIterator(包括 BidirectionalIterator)一起使用,还可以利用 RandomAccessIterator.

支持的功能

(强调我的)

Complexity

Linear.

However, if InputIt additionally meets the requirements of RandomAccessIterator, complexity is constant.

所以你可以直接使用它而不考虑迭代器的类别,std::advance会为你做最好的选择。例如

std::advance(iter, 3);

iter = std::next(iter, 3);

A std::list::iterator 不是 Random Access Iterator. It is not possible to "jump ahead" several elements in a list, you must iterate through the list until you reach the desired element. You can use std::advance,它将根据迭代器类别推断出推进迭代器的最佳方法。在 std::list::iterator 的情况下,它将在循环中递增迭代器。

原因很简单,+= 运算符没有为您正在使用的双向迭代器定义。

对于所有迭代器,至少有:

  • 可复制且可破坏,即 X b(a);b = a;
  • 可以递增,即++aa++

其他一切都取决于迭代器的类型检查 table here:

如您所见,随机访问迭代器可以解决问题。