//vector存放内置数据类型 #include <bits/stdc++.h> using namespace std; void myprint(int val) { cout << val << endl; } void test01() { vector<int> v; // 1插入 v.push_back(10); v.push_back(20); v.push_back(30); v.push_back(40); // 2遍历 // 通过迭代器访问容器中数据 // 第一种遍历方式: vector<int>::iterator itbegin = v.begin(); // 起始迭代器 指向容器中第一个元素 vector<int>::iterator itend = v.end(); // 结束迭代器 只想容器中最后一个元素的下一个位置 while (itbegin != itend) { cout << *itbegin << endl; // 解引用 itbegin++; } // 第二种遍历方式:(常用) for (vector<int>::iterator it = v.begin(); it != v.end(); it++) { cout << *it << endl;// 解引用 } // 第三种遍历方式:用for_each(stl提供的遍历算法) for_each(v.begin(), v.end(), myprint); } int main() { test01(); }
// vector存放自定义数据类型 #include <bits/stdc++.h> using namespace std; class person { public: person(string name, int age) { this->name = name; this->age = age; } string name; int age; }; void test01() { vector<person> v; person p1("a", 10); person p2("b", 20); person p3("c", 30); person p4("d", 40); person p5("e", 50); /// 向容器中添加数据 v.push_back(p1); v.push_back(p2); v.push_back(p3); v.push_back(p4); v.push_back(p5); // 开始遍历容器数据 for (vector<person>::iterator it = v.begin(); it != v.end(); it++) { //*it为解引用指针it,得到person。it为指针,直接用->得到指针所指的值也可。 cout << "name:" << (*it).name << " age:" << (*it).age << endl; // cout << "name:" << it->name << " age:" << it->age << endl; } } void test02() { // 存放自定义数据类型的指针 即保存地址到容器中 vector<person *> v; person p1("a", 10); person p2("b", 20); person p3("c", 30); person p4("d", 40); person p5("e", 50); /// 向容器中添加数据 v.push_back(&p1); v.push_back(&p2); v.push_back(&p3); v.push_back(&p4); v.push_back(&p5); // 开始遍历容器数据 for (vector<person *>::iterator it = v.begin(); it != v.end(); it++) { //*it解出指针person*,所以it为二级指针,*it为指针,要用->得到指针所指的值 cout << "name:" << (*it)->name << " age:" << (*it)->age << endl; } } int main() { // test01(); test02(); }
// vector容器嵌套容器(多位数组) #include <bits/stdc++.h> using namespace std; void test01() { vector<vector<int>> v; // 创建小容器 vector<int> v1; vector<int> v2; vector<int> v3; vector<int> v4; // 向小容器中添加数据 for (int i = 0; i < 4; i++) { v1.push_back(i + 1); // 1234 v2.push_back(i + 2); // 2345 v3.push_back(i + 3); // 3456 v4.push_back(i + 4); // 4567 } // 将小容器插入到大容器中 v.push_back(v1); v.push_back(v2); v.push_back(v3); v.push_back(v4); // 通过大容器遍历数据 for (vector<vector<int>>::iterator it = v.begin(); it != v.end(); it++) { //(*it)为vector<int> for (vector<int>::iterator vit = (*it).begin(); vit != (*it).end(); vit++) { //(*vit)为int cout << (*vit) << " "; } cout << endl; } } int main() { test01(); }