原文位址: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;
}
運作結果:

發現資料還是沒有被銷毀阿。。。
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
| | Edit & Run |
Output:
|
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