下面是一个容器的基本使用范例,在此之前,先来看看vector。vector是namespace std内的template。其定义如下:
namespace std{ template> class vector;}
来看看实际例子中是如何使用的:
在文件vectorpra.h中:
class People{protected: string Sex; string name; int age;};class Student: public People {private: int grade;public: void SetSex(string wsex){ Sex=wsex; } string GetSex() const{ return Sex; } void SetName(string stuname){ name=stuname; } string GetName() const{ return name; } void SetAge(int year){ age=year; } int GetAge() const{ return age; } void SetGrade(int gradeyear){ grade=gradeyear; } int GetGrade() const{ return grade; }};typedef vectorStudentArray;class stuManager {public: StudentArray m_array; void CreateStuInfo(string Aname,string Asex,int Aage, int Agrade); void PrintStuInfo(Student stu);};
在文件vector.cpp中:
void stuManager::CreateStuInfo(string Aname,string Asex,int Aage, int Agrade){ Student STU; STU.SetName(Aname); STU.SetSex(Asex); STU.SetAge(Aage); STU.SetGrade(Agrade); stuManager::m_array.push_back(STU);}void stuManager::PrintStuInfo(Student stu){ cout<<"Name ="<< <<"Sex ="< < <<"Age ="< < <<"Grade="< <
在main.cpp中:
int main(void){ stuManager MyClass; MyClass.m_array.reserve(10); //保留10个元素的存储空间 MyClass.CreateStuInfo("Kaier","Male",14 ,3); MyClass.CreateStuInfo("Randy","FMale",13 ,3); MyClass.CreateStuInfo("Parker","Male",15 ,3); MyClass.CreateStuInfo("Coco","FMale",13 ,3); MyClass.CreateStuInfo("Joe","Male",12 ,3); MyClass.CreateStuInfo("Amy","FMale",15 ,3); for (int i = 0; i < MyClass.m_array.size();i++) { MyClass.PrintStuInfo(MyClass.m_array.at(i)); } getchar(); getchar(); return 0;}