2014年01月21日 星期二 20:21
vector是C++ STL Container中重要的一员,应该是最经常使用的一个数据结构,可以动态增长和收缩,可以随机访问,非常灵活。编程示例如下:
#include <iostream> #include <vector> #include <string> using namespace std; template <class T> void print_elements(T& elem) { for(auto &x : elem) { cout << x << " "; } cout << endl; } int main(int argc, char **argv) { vector<int> v; v.reserve(10); cout << v.capacity() << endl; for(unsigned int i=0;i<6;i++) { v.push_back(i*i); } print_elements(v); cout << "size: " << v.size() ; cout << ", capacity: " << v.capacity() << endl; v.shrink_to_fit(); cout << "size: " << v.size() ; cout << ", capacity: " << v.capacity() << endl; auto v2=v; cout << "size: " << v2.size() cout << ", capacity: " << v2.capacity() << endl; cout << "v == v2 ? " << (v == v2) << endl; vector<int> v3({1,3,4,5,6,7}); print_elements(v3); v3.assign(10,3); print_elements(v3); v2.swap(v3); print_elements(v3); for(auto &x : v3) { x=x*x; } for(auto i=v3.size();i>0;i--) { cout << v3.at(i-1) << " " << v3[i-1] << " " ; } cout << endl; print_elements(v3); v3.resize(3); print_elements(v3); v3.erase(v3.begin()+1); print_elements(v3); v3.clear(); vector<bool> v4; v4.assign(10,false); for(auto i=v4.size();i>0;i--) { cout << v4.at(i-1) << " " ; } cout << endl; for(auto i=v4.size();i>0;i--) { if(i % 2 == 0 ) { v4[i-1].flip(); } } for(auto i=v4.size();i>0;i--) { cout << v4.at(i-1) << " " ; } cout << endl; return 0; }
参考资料:
Zeuux © 2024
京ICP备05028076号