C++中在容器Vector中使用結構體Struct
阿新 • • 發佈:2019-01-04
簡單介紹 具體請看 http://www.cnblogs.com/qyaizs/articles/2039101.html
#include <iostream>
#include <vector>
using namespace std ;
struct Rect
{
int Dir;
int Ini;
int Inj;
};
int main()
{
Rect rect;
vector<Rect>vec;
for (int i=0;i<10;i++)
{
rect.Dir=i;
rect.Ini=i+2;
rect.Inj=i*i;
vec.push_back(rect);
}
for (int i=0;i<vec.size();i++)
{
cout<<vec[i].Dir<<"\t"<<vec[i].Ini<<"\t"<<vec[i].Inj<<endl;
}
system("pause");
}
如果想做成全域性的結構體容器的話 參考如下
//test.h #ifndef _TEST_H #define _TEST_H #include <iostream> #include <vector> struct Student { int age; int id; }; class TEST { public: TEST(){}; ~TEST(){}; void prrr(); }; class CVX_FEA { public: CVX_FEA(); ~CVX_FEA(); void daoru(); void pr(); Student ZhiFei; std::vector<Student>Information; void pri(); TEST* PENV; }; #endif
//test.cpp #include "test.h" #include <iostream> using namespace std ; CVX_FEA::CVX_FEA() { cout<<"建構函式"<<endl ; } CVX_FEA::~CVX_FEA() { cout<<"解構函式"<<endl ; } void CVX_FEA::daoru() { for (int i=0;i<10;i++) { ZhiFei.age=i+3; ZhiFei.id=i^2; Information.push_back(ZhiFei); } } void CVX_FEA::pr() { daoru(); for (int i=0;i<10;i++) { cout<<Information[i].age<<endl ;; cout<<Information[i].id<<endl ; } PENV->prrr(); } void CVX_FEA::pri() { cout<<"ghjk"; } void TEST::prrr() { cout<<"SDSFAF"; } int main() { CVX_FEA FEA; FEA.pr(); system("pause"); }