vector存儲類對象:
#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;
class point{
public:
point(int _x =0, int _y =0 ):x(_x), y(_y){};
int GetX(void) const { return x;}
int GetY(void) const { return y;}
private:
int x,y;
};
int _tmain(int argc, _TCHAR* argv[])
{
vector<point> vec;
vec.push_back(point(1,2));
vec.push_back(point(2,2));
for (auto itr = vec.cbegin(); itr != vec.cend(); ++itr)
{
cout<<"point("<<itr->GetX()<<","<<itr->GetY()<<")"<<endl;
}
getchar();
return 0;
}
輸出結(jié)果:
result1.PNG
存儲類指針:
#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;
class Point{
public:
Point(int x =0, int y =0 ):x(x), y(y){};
int GetX(void) const { return x;}
int GetY(void) const { return y;}
private:
int x,y;
};
int _tmain(int argc, _TCHAR* argv[])
{
//存儲類指針
vector<Point*> vecptr;
for (int i = 0; i < 5; i++)
{
Point pt;
Point* ptr=&pt; //此種方法為pt分配的地址都是一樣的锣杂,不可行
vecptr.push_back(ptr);
}
for (int i = 0; i < vecptr.size(); i++)
{
cout<<vecptr[i]<<endl; //地址都相同
}
cout<<endl;
cout<<endl;
vecptr.clear(); //清空矢量容器
for (int i = 0; i < 5; i++)
{
Point* ptr=new Point(); //此法可行菠发,分配成功返回地址
vecptr.push_back(ptr);
}
for (int i = 0; i < vecptr.size(); i++)
{
cout<<vecptr[i]<<endl; //地址都不同,可行
}
cout<<endl;
//存儲類對象
vector<Point> vec;
for (int i = 0; i < 10; i++)
{
Point pt;
vec.push_back(pt);
}
for (int i = 0; i < vec.size(); i++)
{
cout<<&vec[i]<<endl;
}
getchar();
return 0;
}
輸出結(jié)果:
result2.PNG
指向基類的vector用法:
#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;
class Polygon
{
protected:
int width, height;
public:
void set_values (int a, int b)
{
width=a;
height=b;
}
virtual int area() const = 0;
};
class Rectangle: public Polygon
{
public:
virtual int area() const
{
return width*height;
}
};
class Triangle: public Polygon
{
public:
virtual int area() const
{
return width*height/2;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
Rectangle rect;
Triangle trgl;
vector<Polygon*> vec; //指向基類的矢量容器
Polygon * ppoly1 = ▭
ppoly1->set_values (4,5);
vec.push_back(ppoly1);
Polygon * ppoly2 = &trgl;
ppoly2->set_values (4,5);
vec.push_back(ppoly2);
for (auto itr = vec.cbegin(); itr != vec.cend(); ++itr) //不知道用什么類型時可以選擇用auto
{
cout << (*itr)->area() << '\n';
}
getchar();
return 0;
}
輸出結(jié)果:
20
10