STL之二:vector容器用法詳解
阿新 • • 發佈:2019-01-09
// vectorsample.cpp : 定義控制檯應用程式的入口點。 // #include "stdafx.h" #include<iostream> #include<vector> #include<string> using namespace std; class Student { public: string m_strNO; string m_strName; string m_strSex; string m_strDate; public: Student(string strNO,string strName,string strSex,string strDate) { m_strNO = strNO; m_strName = strName; m_strSex = strSex; m_strDate = strDate; } void Display() { cout<<m_strNO<<"\t"; cout<<m_strName<<"\t"; cout<<m_strSex<<"\t"; cout<<m_strDate<<"\t"; } }; class StudCollect { vector<Student> m_vStud; public: void Add(Student &s) { m_vStud.push_back(s); } Student* Find(string strNO) { bool bFind = false; int i; for(i = 0;i < m_vStud.size();i++) { Student& s = m_vStud.at(i); if(s.m_strNO == strNO) { bFind = true; break; } } Student *s = NULL; if(bFind) s = &m_vStud.at(i); return s; } }; int _tmain(int argc, _TCHAR* argv[]) { Student s1("1001","zhangsan","boy","1988-10-10"); Student s2("1002","lisi","boy","1988-8-25"); Student s3("1003","wangwu","boy","1989-2-14"); StudCollect s; s.Add(s1); s.Add(s2); s.Add(s3); Student *ps = s.Find("1002"); if(ps) ps->Display(); return 0; }
程式碼執行例項如下: