简体   繁体   English

从std :: list清除元素的顺序是什么?

[英]What is the order of clearing elements from std::list?

I want to clear the contents of some std::list . 我想清除一些std::list的内容。 The order of removing of elements is important for me. 删除元素的顺序对我来说很重要。 According to output of the following test program, the order is from first to last element. 根据以下测试程序的输出,顺序是从第一个到最后一个元素。 Is it guaranteed to be so? 是否保证如此? It was not clear for me from C++2003 standard. 我不清楚C ++ 2003标准。

#include <list>
#include <iostream>

struct A
{
  A(int i) : I(i) {}
  ~A() { std::cout << I << std::endl; }
  int I;
};

int main()
{
  std::list<A> l;
  l.push_back(A(1));
  l.push_back(A(2));
  l.push_back(A(3));

  std::cout << "clearing list" << std::endl;
  l.clear();
}

ideone link 意想不到的联系

不,它没有定义,你不应该依赖它。

No it is not defined. 不,它没有定义。

The standard only specifys that whenever you call a.clear() it will be resolved as a.erase(q1,q2) and it just specify's the erase will erase all the elements in the range [q1,q2) but it does not specify the order in which it will do so. 标准只规定,无论何时调用a.clear()它都将被解析为a.erase(q1,q2) ,它只是指定擦除将擦除[q1,q2)范围内的所有元素,但它没有指定它将这样做的顺序。

Just for completeness, the C++11 standard does not determine the order of destruction of any sequence containers , of which std::list is a member. 为了完整起见,C ++ 11标准不确定任何sequence containers的破坏sequence containers ,其中std::list是其成员。 It only states that all the elements are destroyed, all references, pointers and iterators referring to the elements are invalidated, and the past the end iterator may be invalidated. 它只声明所有元素都被销毁,引用元素的所有引用,指针和迭代器都是无效的,并且过去的结束迭代器可能会失效。 Concerning clear() , it makes no mention of erase() , begin() or end() , unlike hte C++03 standard. 关于clear() ,它没有提到erase()begin()end() ,这与hte C ++ 03标准不同。

From c++03 standard: 从c ++ 03标准:

Table 67—Sequence requirements (in addition to container) ... 表67-序列要求(除容器外)......

a.clear() 明确()

assertion/note: void erase(begin(), end()) 断言/注意:void erase(begin(),end())

post: size() == 0. post:size()== 0。

Since it starts deleting elements from "begin" I think is safe to infers that they will be deleted in order. 由于它开始从“开始”删除元素,我认为可以安全地推断它们将按顺序删除。 Otherwise will be a performance penalty to random access list elements. 否则将对随机访问列表元素造成性能损失。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM