#include <algorithm> //系统标准算法头文件
//普通指针也是一种迭代器
void tes01()
{
int arr[]={1,2,3,4};
int *p=arr;
for(int i=0;i<arr.size()-1;i++)
{
cout<<**(p++)<<endl;
}
}
//回调函数
void myPrint(int val)
{
cout << val << endl;
}
//内置属性类型
void test02()
{
vector<int> v;
v.pushback(10);
v.pushback(20);
//通过迭代器可以 遍历容器
//每个容器都有自己专属的迭代器
vector<int>::iterator itBegin=v.begin();//起始编译器
vector<int>::iterator itEnd=v.end();//结束迭代器
//第一种遍历方式
while(itBegin != itEnd)
{
cout<<*itBegin<<enl;
}
//第二种遍历方式
for(vector<int> iterator it=v.begin();it!=v.end();it++)
{
cout<<*it<<endl;
}
//第三种遍历方式 利用系统提供算法
for_each(v.begin(), v.end(), myPrint);
}
//自定义数据类型
class Person
{
public:
Person(string name, int age)
{
this->m_Name = name;
this->m_Age = age;
}
string m_Name;
int m_Age;
};
void test03()
{
vector<Person> v;
Person p1("aaa", 10);
Person p2("bbb", 20);
Person p3("ccc", 30);
Person p4("ddd", 40);
v.push_back(p1);
v.push_back(p2);
v.push_back(p3);
v.push_back(p4);
//遍历
for (vector<Person>::iterator it = v.begin(); it != v.end();it++)
{
// *it --- Person类型 it --- 指针
cout << "姓名: " << (*it).m_Name << " 年龄: " << it->m_Age << endl;
}
}
简单STL迭代或遍历
最新推荐文章于 2024-04-07 09:47:46 发布