vector向量是一种随机访问的数组类型,提供了对数组元素的快速和随机访问,以及在序列尾部快速、随机的插入和删除操作。其大小可变,在需要时可以改变数组大小
头文件要导入#include<vector>
为整型值创建一个空std::vector对象可以使用这样的语句
std::vector<int>intvector
包括vector模板中有很多种方法可以调用 下面是测试源码,如需自取
#include<iostream> #include<vector> #include<stdarg.h> using namespace std; using std::cout; using std::endl; using std::vector; int mai(int argc, char* argv[]) { vector<int>v1, v2; v1.reserve(10); v2.reserve(10); v1 = vector<int>(8, 7); int array[8] = { 1,1,54,24,131,42,42,1331 }; v2 = vector<int>(array, array + 8); cout << "v1容量" << v1.capacity() << endl; cout << "v2容量" << v2.capacity() << endl; for (decltype(v2.size())i = 0; i < v1.size(); i++) { cout << " " << v1[i]; } cout << endl; cout << "v2容量" << v2.capacity() << endl; cout << "v2当前各项" << endl; for (vector<int>::size_type i = 0; i < v1.size(); i++) { cout << " " << v2[i] << endl; } cout << endl; v1.resize(0); cout << "v1的容量通过resize函数变成0" << endl; if (!v1.empty()) cout << "v1容量" << v1.capacity() << endl; else cout << "v1是空的" << endl; cout << "将v1容量扩展为8" << endl; v1.resize(8); cout << "v1当前各项" << endl; for (decltype(v1.size())i = 0; i < v1.size(); i++) { cout << "" << v1[i] << endl; } cout << endl; v1.swap(v2); cout << "v1与v2交换了" << endl; cout << "v1当前各项" << endl; cout << "v1容量" << v1.capacity() << endl; for (decltype(v1.size())i = 0; i < v1.size(); i++) { cout << " " << v1[i] << endl; } cout << endl; v1.push_back(3); cout << "v1从后边加入了元素3" << endl; cout << "v1容量" << v1.capacity() << endl; for (decltype(v1.size())i = 0; i < v1.size(); i++) { cout << " " << v1[i] << endl; } cout << endl; v1.erase(v1.end() - 2); cout << "删除了倒数第二个元素" << endl; cout << "v1容量" << v1.capacity() << endl; cout << "v1当前各项" << endl; for (vector<int>::size_type i = 0; i < v1.size(); i++) { cout << " " << v1[i] << endl; } cout << endl; v1.pop_back(); cout << "v1通过栈操作放走了最后的元素" << endl; cout << "v1当前各项" << endl; cout << "v1容量" << v1.capacity() << endl; for (vector<int>::size_type i = 0; i < v1.size(); i++) { cout << " " << v1[i] << endl; } cout << endl; return 0; }