STL中有push_back 等方法 可以将一个数据放入容器中。
在push_back中完成的是值拷贝,而不仅仅是地址的复制。
#include <vector>
#include <iostream>
using namespace std;
typedef struct point{
int x;
int y;
}Point;
ostream& operator<<(ostream& output, const Point &a)
{
return output << a.x <<" "<< a.y;
}
int main(){
Point * a = new Point;
vector<Point> PointList;
a->x = 3;
a->y = 4;
PointList.push_back(*a);
a->x = 4;
a->y = 4;
PointList.push_back(*a);
a->x = 5;
a->y = 4;
PointList.push_back(*a);
delete a;
for (vector<Point>::iterator i = PointList.begin(); i != PointList.end(); i++){
cout << (*i)<< endl;
}
return 0;
}
当然如果用类(如Point类)构造的容器来说如果有new/malloc分配的空间,要重写复制构造函数才不会出问题。