c++ - 使用 std::list 作为循环列表是否安全?

标签 c++ list iterator std

所以标准中定义了递增或递减 end() 迭代器?在 Linux 上,begin() 被实现为 end()++。

#include <list>
#include <iostream>

int main()
{
  std::list<int> numbers;
  for (int i = 0; i < 10; i++)
    numbers.push_back(i);

  auto it = numbers.begin();
  int count = 3;
  while (count)
  {
    std::cout << *it++;
    if (it == numbers.end())
    {
      ++it; // is this ok ???
      --count;
      std::cout << '\n';
    }
  }
}

所以每个平台上的输出总是一样的?

输出:

0123456789
0123456789
0123456789

最佳答案

递增从 end() 返回的迭代器任何标准 C++ 库容器都会导致未定义的行为。由于 std::list<T> 的大多数实现通用的实现细节它可能会增加 list.end()但不能保证它确实如此。

关于c++ - 使用 std::list 作为循环列表是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47607613/

相关文章:

c++ - 迭代器拼接列表后存储了错误的值

c++ - 如何更改此标记化过程以处理多行文本文件?

c++ - vector<int>::const_iterator 是一个output_iterator吗?

c++ - boost 侵入式交换

python - 检查封闭的元组

java -\n 从文件读取到列表然后输出时不起作用。 java

css - 在列表中正确包装文本

c++ - 出队不适用于从双链表继承的队列类

c++ - Intel HD 3000 上正确的 OpenGL 初始化是什么?

c++ - 从 .txt 文件中读取一行并插入到变量中