论C++11 中vector的N种遍历方法
来源:互联网 发布:苹果主屏有什么软件 编辑:程序博客网 时间:2024/06/05 22:39
随着C++11标准的出现,C++标准添加了许多有用的特性,C++代码的写法也有比较多的变化。
vector是经常要使用到的std组件,对于vector的遍历,本文罗列了若干种写法。
(注:本文中代码为C++11标准的代码,需要在较新的编译器中编译运行)
假设有这样的一个vector:(注意,这种列表初始化的方法是c++11中新增语法)
vector<int> valList = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
需要输出这个vector中的每个元素,测试原型如下:
void ShowVec(const vector<int>& valList){}int main(int argc, char* argv[]){ vector<int> valList = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; ShowVec(valList); return 0;}
下面就开始我们的茴香豆的N种写法吧 !
方法零,对C念念不舍的童鞋们习惯的写法:
void ShowVec(const vector<int>& valList){ int count = valList.size(); for (int i = 0; i < count;i++) { cout << valList[i] << endl; }}
或者
void
ShowVec(
const
vector<
int
>& valList)
{
int
count = valList.size();
for
(
int
i = 0; i < count;i++)
{
cout << valList.at(i) << endl;
}
}
方法一,大家喜闻乐见的for循环迭代器输出,(注意,此处使用了C++11中新增的标准库容器的cbegin函数)
void ShowVec(const vector<int>& valList){ for (vector<int>::const_iterator iter = valList.cbegin(); iter != valList.cend(); iter++) { cout << (*iter) << endl; }}
或者使用c++新增的语义auto,与上面差不多,不过能少打几个字:
void ShowVec(const vector<int>& valList){ for (auto iter = valList.cbegin(); iter != valList.cend(); iter++) { cout << (*iter) << endl; }}
方法二,for_each加函数:
template<typename T>void printer(const T& val){ cout << val << endl;}void ShowVec(const vector<int>& valList){ for_each(valList.cbegin(), valList.cend(), printer<int>);}
方法三,for_each加仿函数:
template<typename T>struct functor{ void operator()(const T& obj) { cout << obj << endl; }};void ShowVec(const vector<int>& valList){ for_each(valList.cbegin(), valList.cend(), functor<int>());}
方法四,for_each加Lambda函数:(注意:lambda为c++11中新增的语义,实则是一个匿名函数)
void ShowVec(const vector<int>& valList){ for_each(valList.cbegin(), valList.cend(), [](const int& val)->void{cout << val << endl; });}
方法五,for区间遍历:(注意,for区间遍历是c++11新增的语法,用于迭代遍历数据列表)
for (auto val : valList){ cout << val << endl;}
etc.
本文纯属无聊所写,期待更多蛋疼的方法!
最后:
C++11相比C++98/03还是更新了挺多东西的,目前g++最新版已完全支持C++11标准,这意味着开源社区的新的project必然将迁移到最新的C++11标准上,平时参与/阅读/参考开源代码的童鞋们需要学习了。
作为C++程序员,我们当然要与时俱进,拥抱C++11!
此处推荐一个学习C++11的github链接:https://github.com/sib9/cpp1x-study-resource
下面附一个C++11更新列表:
--------------------------------------------------------
- 论C++11 中vector的N种遍历方法
- 论C++11 中vector的N种遍历方法
- 论C++11 中vector的N种遍历方法
- C++之vector中元素的N种遍历
- struts2 遍历Map的N中方法
- 遍历vector的两种方法
- Java Vector遍历的五种方法
- vector容器的三种遍历方法
- vector容器的三种遍历方法
- 遍历json数据的n种方法
- Objective-C中,遍历数组的四种方法
- c遍历lua中table的方法
- 谈谈vector容器的三种遍历方法
- 谈谈vector容器的三种遍历方法
- 在linux shell中使用for遍历产生的递增数字序列的N种方法
- 在linux shell中使用for遍历产生的递增数字序列的N种方法
- 真正快速的std::vector遍历方法
- 真正快速的std::vector遍历方法
- English for me
- 自定义函数
- D
- 队列<queue>中常用的函数
- Java网络基础,Socket通信基础
- 论C++11 中vector的N种遍历方法
- C++虚函数和虚继承
- HTML 简介
- 【git入门】git常用命令
- 【HDU】1312--Red and Black(DFS)
- E
- python http通信中字典,列表等数据结构unicode转utf-8的转码问题
- 1125
- 最小割+强连通分量 COGS 426 血帆海盗