1 #include <iostream> 2 #include <vector> 3 #include <string> 4 #include <stdio.h> 5 6 7 void test_vector_clear() { 8 std::cout<<"before vector: "; 9 getchar(); 10 11 std::vector<std::string> vtList; 12 vtList.reserve(1000000); 13 14 for (int i=0; i<1000000; ++i) { 15 vtList.push_back("hello world!"); 16 } 17 18 std::cout << "fill vetor done "; 19 getchar(); 20 21 vtList.clear(); 22 std::cout << "clear done:the vtList[0]=" 23 << vtList[0] << " "; 24 getchar(); 25 26 { 27 std::vector<std::string> tmp; 28 vtList.swap(tmp); 29 } 30 31 32 std::cout<<"swap done "; 33 getchar(); 34 } 35 36 int main(void) { 37 test_vector_clear(); 38 39 return 0; 40 }
运行结果如下:
下面文字描述下进程运行的各个阶段及相应状态的内存情况
阶段 内存大小
before vector: 1232
fill vector done 32648
clear done 32648
swap done 1400
结论:
clear清空元素但不会释放内存;如果想要释放内存可以考虑使用swap函数;