容器 可以实现 数据结构 与 算法 的分离。
eg:
1、容器装基础变量类型
vector<int>lunais; lunais.push_back(1); lunais.push_back(2); lunais.push_back(3); 可使用迭代器进行遍历: for(vector<int>::interator it = lunais.begin(); it != luanis.end(); ++it) { cout << *it << endl; }
2、容器装 元素
class Teacher { public: int age; char name[64]; public: void printT() { cout << "age: " << age << endl; } } Teacher t1,t2; t1.age = 30; t2.age = 32; vector<Teacher> lunais; lunais.push_back(t1); lunais.push_back(t2); for(vector<Teacher>::interator it = lunais.begin(); it != luanis.end(); ++it) { cout << it->age<< endl; }
3.容器装指针
Teacher *p1,*p2; p1 = &t1; p2 = &t2; vector<Teacher *> lunais; lunais.push_back(p1); lunais.push_back(p2); for(vector<Teacher *>::interator it = lunais.begin(); it != luanis.end(); ++it) { cout <<(*it)->age<< endl; }
时间: 2024-10-28 16:38:09