1.vector基本概念
2.vector构造函数
#include<vector> #include<iostream> using namespace std; void print(vector<int>& v) { for (vector<int>::iterator it = v.begin(); it != v.end(); it++) { cout << *it << " "; } } void test() { vector<int> v1; for (int i = 0; i < 10; i++) { v1.push_back(i + 1); }; print(v1); vector<int> v2(v1.begin(), v1.end()); print(v2); vector<int> v3(10, 100); print(v3); vector<int> v4(v3); print(v4); } int main() { test(); return 0; }
3.vector赋值操作
#include<iostream> #include<vector> using namespace std; void print(vector<int>& v1) { for (vector<int>::iterator it = v1.begin(); it != v1.end(); it++) { cout << *it << " "; } } void test() { vector<int> v1; for (int i = 0; i < 5; i++) { v1.push_back(i + 1); } print(v1); cout << endl; vector<int> v2; v2 = v1; print(v1); cout << endl; vector<int> v3; v3.assign(v1.begin(), v1.end()); print(v3); cout << endl; vector<int> v4; v4.assign(10, 100); print(v4); cout << endl; } int main() { test(); return 0; }
4.vector容量和大小
#include<iostream> #include<vector> using namespace std; void print(vector<int>& v1) { for (vector<int>::iterator it = v1.begin(); it != v1.end(); it++) { cout << *it << " "; }; cout << endl; } void test() { vector<int> v1; for (int i = 0; i < 5; i++) { v1.push_back(i + 1); } print(v1); if (v1.empty()) { cout << "it is empty" << endl; } else { cout <<"v1.size="<< v1.size() << endl; cout << "v1.capacity()" << v1.capacity() << endl; } v1.resize(10); cout << "the resize is" << " "; print(v1); cout << endl; //resize 重新指定大小 ,若指定的更大,默认用0填充新位置,可以利用重载版本替换默认填充 v1.resize(10, 2); print(v1); } int main() { test(); return 0; }
5.vector数据存取
#include<iostream> #include<vector> using namespace std; void test() { vector<int> v1; for (int i = 0; i < v1.size(); i++) { cout << v1[i] << " "; } cout << endl; for (int j = 0; j < v1.size(); j++) { cout << v1.at(j) << " "; } cout << endl; cout << "v1的第一个元素" << v1.front() << endl; cout << "v1的最后一个元素" << v1.back() << endl; } int main() { test(); return 0; }
6.vector预留空间
#include<iostream> #include<vector> using namespace std; void test() { vector<int> v1; v1.reserve(100000); } int main() { test(); return 0; }
7.vector互换容器
#include<iostream> #include<vector> using namespace std; void print(vector<int>& v1) { for (vector<int>::iterator it = v1.begin(); it != v1.end(); it++) { cout << *it << " "; } cout << endl; cout << "-------------------------------------------------" << endl; } void test() { vector<int> v1; for (int i = 0; i < 10; i++) { v1.push_back(i + 1); } print(v1); vector<int> v2; for (int i = 10; i > 0; i--) { v2.push_back(i + 1); } print(v2); cout << "交换后的数据" << endl; v1.swap(v2); print(v1); print(v2); } int main() { test(); return 0; }