int a[] = {3, 2, 3, 5, 7, 5, 9 ,2}; std::vector<int> vec(a, a+sizeof(a)/sizeof(int) ); std::sort(vec.begin(), vec.end() ); vector<int>::iterator iter_end; iter_end = std::unique(vec.begin(), vec.end() ); vec.erase(iter_end, vec.end() );
对如下函数一一说明:
sort:从小到大排序。程序执行到sort后的结果:
unique:元素去重,unique返回重复元素开始的位置,并且会改变原vec的向量值。程序执行到unique后的结果(输出此时的Vec):
earse:删除元素。程序执行到erase后的结果(输出此时的Vec):
完成对vector的去重和排序
另外说明vertor的几个属性
capacity:系统现在给vector分配的内存大小
size:vector现有的数据大小
max_size:系统可以给给vector分配的最大容量
// comparing size, capacity and max_size #include <iostream> #include <vector> int main () { std::vector<int> myvector; // set some content in the vector: for (int i=0; i<100; i++) myvector.push_back(i); std::cout << "size: " << (int) myvector.size() << ' '; std::cout << "capacity: " << (int) myvector.capacity() << ' '; std::cout << "max_size: " << (int) myvector.max_size() << ' '; return 0; }
结果: size: 100 capacity: 128 max_size: 1073741823
再给个例子补充一下erase的用法:
// vector_erase.cpp // compile with: /EHsc #include <vector> #include <iostream> using namespace std; int main() { vector <int> vec; vector <int>::iterator pos; vec.push_back(10); vec.push_back(20); vec.push_back(30); vec.push_back(40); vec.push_back(50); cout << "Capacity = " << vec.capacity() << endl; cout << "vec ="; for (pos = vec.begin(); pos != vec.end(); ++pos) { cout << " " << *pos; } cout << endl; vec.erase(vec.begin()); cout << "vec = "; for (pos = vec.begin(); pos != vec.end(); ++pos) { cout << " " << *pos; } cout << endl; vec.erase(vec.begin() + 1, vec.begin() + 3); cout << "vec = "; for (pos = vec.begin(); pos != vec.end(); ++pos) { cout << " " << *pos; } cout << endl; cout << "Capacity after erase calls = " << vec.capacity() << endl; }
结果: Capacity = 6 vec = 10 20 30 40 50 vec = 20 30 40 50 vec = 20 50 Capacity after erase calls = 6
来源:https://msdn.microsoft.com/en-us/library/ceh559x2.aspx