STLvector中的clear方法(18)


STLvector中的clear方法(18)

public member function
<vector>

std::vector::clear

void clear() noexcept;
Clear content

Removes all elements from the vector (which are destroyed), leaving the container with a size of 0.

移除vector内所有元素(并销毁他们),使容器大小为变为0(size而不是capacity)。

例子:

#include <iostream>
#include <vector>
using namespace std;
int main()
{
	vector<int> vi={10,20,30};
	cout<<"size="<<vi.size()<<endl;
	cout<<"capacity="<<vi.capacity()<<endl;
	vi.clear();
	cout<<"size="<<vi.size()<<endl;
	cout<<"capacity="<<vi.capacity()<<endl;
	cout<<"vi[1]="<<vi[1]<<endl;
	
}

运行结果:


发现数据还是没有被销毁阿。。。

A reallocation is not guaranteed to happen, and the vector capacity is not guaranteed to change
due to calling this function. A typical alternative that forces a reallocation is to use swap:

 
vector<T>().swap(x);   // clear x reallocating 
 

不保证会发生重分配,也不保证该函数会改变capacity,另一个备选的发生重分配的是swap。


Parameters

none


Return value

none


Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// clearing vectors
#include <iostream>
#include <vector>

int main ()
{
  std::vector<int> myvector;
  myvector.push_back (100);
  myvector.push_back (200);
  myvector.push_back (300);

  std::cout << "myvector contains:";
  for (unsigned i=0; i<myvector.size(); i++)
    std::cout << ' ' << myvector[i];
  std::cout << '\n';

  myvector.clear();
  myvector.push_back (1101);
  myvector.push_back (2202);

  std::cout << "myvector contains:";
  for (unsigned i=0; i<myvector.size(); i++)
    std::cout << ' ' << myvector[i];
  std::cout << '\n';

  return 0;
}

Output:

myvector contains: 100 200 300
myvector contains: 1101 2202



Complexity

Linear in size (destructions).
This may be optimized to constant complexity for trivially-destructible types (such as scalar
or PODs), where elements need not be destroyed.

复杂度和其大小线性相关(析构)

最优复杂度可能是常量时间复杂度,因为可能其中的元素不需要析构。


Iterator validity

All iterators, pointers and references related to this container are invalidated.

所有的迭代器,指针以及引用都将失效。

#include <iostream>
#include <vector>
using namespace std;
int main()
{
	vector<int> vi={10,20,30};
	cout<<"size="<<vi.size()<<endl;
	cout<<"capacity="<<vi.capacity()<<endl;
	int &ri=vi[0];
	auto it=vi.begin();
	vi.clear();
	cout<<"size="<<vi.size()<<endl;
	cout<<"capacity="<<vi.capacity()<<endl;
	cout<<"vi[1]="<<vi[1]<<endl;
	cout<<"ri="<<ri<<endl;
	cout<<"vi.begin()="<<*it<<endl;
	
}


坑我的吧,怎么都没有失效??


Data races

The container is modified.
All contained elements are modified.

容器将被访问。

所有容器元素都将被修改。


Exception safety

No-throw guarantee: this member function never throws exceptions.

该成员方法不会抛出异常。


//翻译的不好的地方请多多指导,可以在下面留言或者点击左上方邮件地址给我发邮件,指出我的错误以及不足,以便我修改,更好的分享给大家,谢谢。


转载请注明出处:http://blog.csdn.net/qq844352155

2014-8-15

于GDUT





发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注