首先,欢迎并感谢博友进行知识补充与修正。
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
//迭代器三种遍历方式
void Myprint(int e) //回调函数
{
cout << e << endl;
}
void test01()
{
vector<int> v = { 1, 2, 3, 4, 5 };
vector<int>::iterator itBegin = v.begin();
vector<int>::iterator itEnd = v.end();
while (itBegin != itEnd)
{
cout << *(itBegin++) << endl;
}
}
void test02()
{
vector<int> v = { 1, 2, 3, 4, 5 };
for (vector<int>::iterator it=v.begin();it!=v.end();it++)
{
cout << *it << endl;
}
}
void test03()
{
vector<int> v = { 1, 2, 3, 4, 5 };
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 test04()
{
Person p1("大头儿子", 8);
Person p2("小头爸爸", 30);
Person p3("围裙妈妈", 28);
Person p4("隔壁老王", 32);
vector<Person> v;
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
{
cout << "名字:" << (*it).m_name <<" "<< "年龄:" << it->m_age << endl;
}
}
//自定义指针数据类型容器
void test05()
{
Person p1("大头儿子", 8);
Person p2("小头爸爸", 30);
Person p3("围裙妈妈", 28);
Person p4("隔壁老王", 32);
vector<Person*> v;
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*
{
cout << "名字:" << (*(*it)).m_name <<" "<< "年龄:" << (*it)->m_age << endl;
}
}
//嵌套容器
void test06()
{
vector<vector<int>> v;
vector<int> v1;
vector<int> v2;
vector<int> v3;
for (int i = 0; i < 5; i++)
{
v1.push_back(i);
v2.push_back(i + 10);
v3.push_back(i + 100);
}
v.push_back(v1);
v.push_back(v2);
v.push_back(v3);
for (vector<vector<int>> ::iterator vit = v.begin(); vit != v.end(); vit++) //*vit 为vector<int>类型
{
for (vector<int> ::iterator it = (*vit).begin(); it != (*vit).end(); it++)
{
cout << *it << " ";
}
cout << endl;
}
}
//第四种遍历方法 C++11新特性: 范围for语句
void test07()
{
vector<int> v = { 1, 2, 3, 4, 5 };
for (auto e : v)
{
cout << e << " ";
}
cout << endl;
for (auto &e : v)
{
e *= 2;
}
for (auto e : v)
{
cout << e << " ";
}
cout << endl;
}
int main()
{
test07();
system("pause");
}