#include<vector>
#include<algorithm>
#include<iostream>
using namespace std;
//输出的回调函数
void PrintV01(int val) {
cout << val << " ";
}
//STL基本语法
void test01() {
cout << "简易版,整型数据" << endl;
vector<int> v01;
v01.push_back(10);
v01.push_back(20);
v01.push_back(30);
v01.push_back(40);
//通过STL提供的for_each算法进行遍历
//需要获取容器的迭代器,不同容器的迭代器不同
vector<int>::iterator pBegin = v01.begin();
vector<int>::iterator pEnd = v01.end();
cout << "用for_each进行遍历:" << endl;
//三个参数分别是首尾迭代器和自定义的回调函数
//因为容器中u从南方的数据可能是自定义类型,不知道如何打印
for_each(pBegin, pEnd, PrintV01);
cout << "\n用for获取迭代器直接进行遍历:" << endl;
for (vector<int>::iterator it = v01.begin(); it != v01.end(); it++) {
cout << *it << " " << endl;
}
}
//自定义数据类型
class Person {
public:
Person(int m_id, int m_age):id(m_id), age(m_age){}
public:
int id;
int age;
};
//自定义数据类型的回调函数
void PrintV02(Person val) {
cout << "id:" << val.id << " age:" << val.age << endl;
}
//测试2
void test02() {
cout << "\n\n升级版,自定义数据类型" << endl;
vector<Person> v02;
Person p1(01, 17), p2(02, 19), p3(03, 20), p4(04, 18);
v02.push_back(p1);
v02.push_back(p2);
v02.push_back(p3);
v02.push_back(p4);
cout << "用for_each方法遍历:" << endl;
for_each(v02.begin(), v02.end(), PrintV02);
cout << "用for获取迭代器遍历:" << endl;
for (vector<Person>::iterator it = v02.begin(); it != v02.end(); it++) {
cout << "id:" << it->id << " age:" << (*it).age << endl;
}
}
//测试
int main() {
test01();
test02();
cout << endl << endl;
return 0;
}
黑马程序员C++提高1——STL基本理论(容器、迭代器、算法)
最新推荐文章于 2024-03-25 18:05:15 发布