天天看點

STL vector中的clear方法(18) std::vector::clear

原文位址:http://www.cplusplus.com/reference/vector/vector/clear/ public member function <vector>

std::vector::clear

  • C++98
  • C++11
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;
	
}
           

運作結果:

STL vector中的clear方法(18) std::vector::clear

發現資料還是沒有被銷毀阿。。。

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:

不保證會發生重配置設定,也不保證該函數會改變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;
}
           
Edit & Run

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;
	
}
           
STL vector中的clear方法(18) std::vector::clear

坑我的吧,怎麼都沒有失效??

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

繼續閱讀