使用STD ::列表作为循环列表安全吗?

Is it safe to use std::list as a circular list?

本文关键字:列表 安全 循环 STD 使用      更新时间:2023-10-16

因此,在标准中定义了端()迭代器的递增或减少端()迭代器?在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

从任何标准C 库容器中的end()返回的迭代器会导致不确定的行为。由于std::list<T>的大多数实现的实现详细信息,因此可以增加list.end(),但不能保证它可以。

no,这是不行的。std::list迭代器是一个双向学位符,它是前向材料的改进。前向材料状态的++ii++的先决条件:

i是可重访

不适合end(),因为它是列表的最后一项。