c++遍历vector的四种方式

可以使用迭代器,可以使用auto,可以使用for_each,可以使用下标
#include <vector>
vector<int> v1;
v1.push_back(1);
v1.push_back(2);
v1.push_back(3);
v1.push_back(4);

//(1)迭代器遍历方式1
vector<int>::iterator start = v1.begin();//指向容器的初始位置
vector<int>::iterator end = v1.end();//指向元素最后一个位置的后一个位置
while(start != end)
{
    cout << *start << endl;
    start++;
}
//(2)迭代器遍历方式2
//可以把这里的vector<int>::iterator改成auto,会自动推测
//for(auto start = v1.begin(); start != v1.end(); start++)
for(vector<int>::iterator start = v1.begin(); start != v1.end(); start++)
{
    cout << *start << endl;
}
//(3)使用for_each内置算法进行遍历,配合lambda匿名函数
//需要包含头文件#include <algorithm>
for_each(v1.begin(), v1.end(), [](int val)->void { cout << val << endl;});

//(4)使用for_each加函数
template<typename T>
void printer(const T& val)
{
    cout << val << endl;
}
for_each(v1.cbegin(), v1.cend(), printer<int>);

//(5)使用for_each加仿函数
template<typename T>
struch functor
{
    void operator()(const T& obj)
    {
        cout << obj << endl;
    }
};
for_each(v1.cbegin(), v1.cend(), functor<int>());

//(6)数组下标方式1
int count_1 = v1.size();
for(int i = 0; i < count_1; i++)
{
    cout << v1[i] << endl;
}

//(7)数组下标方式2
int count_2 = v1.size();
for(int i = 0; i < count_2; i++)
{
    cout << v1.at(i) << endl;
}

//(8)for区间遍历
for(auto val: v1)
{
    cout << val << endl;
}

 

posted @ 2021-02-20 00:50  花与不易  阅读(4913)  评论(0)    收藏  举报