vector 简介
vector也是容器的一种,里面可以存放相同类型的元素,string容器存放的是char类型元素,若是存放其他类型元素,如:int ,double, 自定义类等类型。
vector 构造
定义方式如下:
void VectDefine() { vector vec1; vector vec2(5,12); for (vector ::iterator iter = vec2.begin(); iter != vec2.end(); ++iter) { cout << *iter << endl; } cout << "*****************" << endl; for each (int value in vec2) { cout << value << endl; }}
vector 容量
void VectCapacity() { vector vec1; cout << vec1.capacity() << endl;// 默认为0 vector vec2(5,222);// 初始化为5个0 cout << vec2.size() << " " << vec2.capacity() << endl; vec2.resize(3); cout << vec2.size() << " " << vec2.capacity() << endl; //cout << vec2[3];// resize()重置原size大小,被裁切的元素被释放掉,通过此行代码访问会崩溃 vector ::iterator iter = vec2.begin(); cout << vec2.capacity() << endl;// 当前空间为5 cout << "--" << *iter << endl; vec2.push_back(12); iter = vec2.begin();// 这里同样要注意迭代器失效的问题 cout << "--" << *iter << endl; cout << vec2.capacity() << endl;// 新增1个元素,空间为7,5 + 5 / 2 vec2.push_back(12); vec2.push_back(12); vec2.push_back(12); cout << vec2.capacity() << endl; 新增3个元素,空间为10,7 + 7 / 2 // vc6.0是以2倍增加}
vector 输出
void VectCout() { vector vec1; for (int i = 0; i < 10; ++i) { vec1.push_back(i); } for (int i = 0; i < vec1.size(); ++i) { cout << vec1[i] << " " << vec1.at(i) << endl; }// at()会抛出异常,[]下标的方式不会}
vector 修改
void VectChange() { // assign() vector vec1; vector vec2; vector vec3; for (int i = 0; i < 10; ++i) { vec1.push_back(i); } vector ::iterator iter_start = vec1.begin() + 2; vector ::iterator iter_end = vec1.end() - 2; vec2.assign(iter_start, iter_end); for (int i = 0; i < vec2.size(); ++i) { cout << vec2.at(i) << endl;// 输出2 3 4 5 6 7 } vec3.assign(5, 333); for (int i = 0; i < vec3.size(); ++i) { cout << vec3.at(i) << endl;//输出5个333 } //clear()/empty()/erase() vec1.clear(); cout << "size:" <<< endl; cout << "is empty:" << vec1.empty() << endl;// 输出is empty:1 vec2.erase(vec2.begin() + 2); for (int i = 0; i < vec2.size(); ++i) { cout << vec2.at(i) << endl;// 输出2 3 5 6 7 } vec2.erase(vec2.begin() + 2, vec2.end() - 1); for (int i = 0; i < vec2.size(); ++i) { cout << vec2.at(i) << endl;// 输出2 3 7 } //insert vec3.insert(vec3.begin() + 1, 444); for (int i = 0; i < vec3.size(); ++i) { cout << vec3.at(i) << endl;// 输出333 444 333 333 333 333 } cout << endl; vec3.insert(vec3.begin() + 1, 2, 555); for (int i = 0; i < vec3.size(); ++i) { cout << vec3.at(i) << endl;// 输出333 555 555 444 333 333 333 333 } cout << endl; vec3.insert(vec3.begin() + 1, vec2.begin(), vec2.end()); for (int i = 0; i < vec3.size(); ++i) { cout << vec3.at(i) << endl;// 输出333 2 3 7 555 555 444 333 333 333 333 }}