vector模板类的存在方便了数据存储,与数组不同的是不需要手动定义占用空间,因此在数据处理方面极大地方便我们编程,当然不好的就是会造成内存自然的浪费,原因可自行百度,下面来介绍一下vector基本上操作,希望对读者有用。
#include "stdafx.h" #include <iostream> #include <vector> using namespace std;
class Point_3D {//定义一个三维数据点类,用于存放三维数据 public: int x, y, z; Point_3D(int a, int b, int c) {//构造函数 x = a; y = b; z = c; } };
int main() { int x[] = { 1,2,3,4,5,6,7,8,9 }; int y[] = { 1,2,3,4,5,6,7,8,9 }; int z[] = { 1,2,3,4,5,6,7,8,9 }; vector<Point_3D> point; for (int i = 0;i < size(x);i++) { Point_3D data(x[i], y[i], z[i]); point.push_back(data);//将数据放到point容器中去 } for (int i = 0;i < point.size();i++) {//将point容器中的数据输出出来,这里仅输出point的x数据 cout << point[i].x<<" "; } cout << endl; // point.erase(point.begin(),point.end()-2);//擦除point中的数据,这里就是删除了1 2 3 4 5 6 7
//------------------------//下面是将temp插入到point中 // Point_3D temp(11, 12, 13); // vector<Point_3D> old; // old.push_back(temp); // point.insert(point.begin() + 5, old.begin(),old.end());//将old容器中的所有数据存在point第五个之后
// old.swap(point);//将old容器的数据与point容器数据的数据交换一下
vector<Point_3D>::iterator pd;//将point容器中的数据输出出来,这里仅输出point的x数据 for (pd = point.begin();pd != point.end();pd++) { cout << (*pd).x << " "; } cout << endl;
return 0; }