#include <iostream>
#include <vector>
#include <algorithm> //for_each()算法头文件
using namespace std;
void test01(void)
{
vector<int>temp;
temp.push_back(10); //尾插法存放数据
temp.push_back(20);
temp.push_back(30);
temp.push_back(40);
temp.push_back(50);
//通过迭代器访问数据
vector<int>::iterator _begin = temp.begin(); //起始迭代器,指向容器中第一个元素
vector<int>::iterator _end = temp.end(); //结束迭代器,指向容器中最后一个元素的后一个元素
while (_begin != _end)
{
cout << *_begin << endl;
_begin++;
}
}
void test02(void)
{
vector<int>temp;
temp.push_back(11); //尾插法存放数据
temp.push_back(22);
temp.push_back(33);
temp.push_back(44);
temp.push_back(55);
for(vector<int>::iterator _begin = temp.begin();_begin != temp.end();_begin++)
cout << *_begin << endl;
}
void print(int num)
{
cout << num << endl;
}
void test03(void)
{
vector<int>temp;
temp.push_back(12); //尾插法存放数据
temp.push_back(23);
temp.push_back(34);
temp.push_back(45);
temp.push_back(56);
for_each(temp.begin(), temp.end(), print);
}
int main()
{
test01(); //第一种访问方式
test02(); //第二种访问方式
test03(); //第三种访问方式(for_each())
return 0;
}
C++ vector迭代器
最新推荐文章于 2024-04-12 08:56:54 发布