C++学习笔记 :vector遍历N种方法
Posted 码农樱木花道
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C++学习笔记 :vector遍历N种方法相关的知识,希望对你有一定的参考价值。
以下5种就是常用的遍历vector的方法:
#include <vector>
#include <iostream>
#include <algorithm> // for_each
using namespace std;
void vector_cout(const int &value)
{
cout << "five method:" << value << endl;
}
int main(void)
{
vector<int> vec;
for (int i = 0; i < 10; i++)
{
vec.push_back(i);
}
//first one, auto is define in C++11
for (auto it = vec.begin(); it != vec.end(); it++)
{
cout << "first method:" << *(it) << endl;
}
//second one
for (int i = 0; i < vec.size(); i++)
{
cout << "second method:" << vec[i] << endl;
}
//third one, before C++11
for (vector<int>::iterator it = vec.begin(); it != vec.end(); it++)
{
cout << "third method:" << *(it) << endl;
}
//four one, auto is define in C++11
for (auto v_element : vec)
{
//v_element is the value of vector, not iterator
cout << "four method:" << v_element << endl;
}
//five one, for_each is define in C++, must include <algorithm>
for_each(vec.cbegin(), vec.cend(), vector_cout);
return 0;
}
以上是关于C++学习笔记 :vector遍历N种方法的主要内容,如果未能解决你的问题,请参考以下文章