C++编程 - 回字有四样写法,你知道么?
来源:互联网 发布:精硕科技 数据分析师 编辑:程序博客网 时间:2024/05/21 09:58
C++编程 - 回字有四样写法,你知道么?
作者:flyfish 2014-3-31
茴香豆的茴字,怎样写的?这次孔乙己一把,循环多种写法,排除while,do while,排除第三方库,Boost库等
开始分茴香豆吃
首先定义一个向量vecCollection,添加10元素,
目的在vecCollection中统计大于5的元素的个数。
填充元素
int nCount = 0; std::vector<int> vecCollection; for (inti=0;i<10;i++) { vecCollection.push_back(i); }
1 数组下标[]访问
int nCount=0;for (UINT i = 0; i < vecCollection.size() ; i++ ) { if(vecCollection[i]>5) { nCount++; } }
2 数组下标at访问
int nCount=0; for (UINT i = 0; i < vecCollection.size() ; i++ ) { if(vecCollection.at(i)>5) { nCount++; } }
at进行了边界检查,而[]没有,例如vecCollection[10],vecCollection.at(10)结果不同。
3迭代器访问
int nCount = 0; std::vector<int>::iterator iter; for ( iter = vecCollection.begin() ; iter !=vecCollection.end() ; iter++ ) { if( (*iter) > 5) { nCount++; } }
迭代器iterator把容器Containers和算法Algorithms分开 计算个累加和很容易 例如
int nSum=std::accumulate(vecCollection.begin(),vecCollection.end(),0);
4 auto简化代码
int nCount = 0; for ( auto iter =vecCollection.begin() ; iter != vecCollection.end() ; iter++ ) { if( (*iter) > 5) { nCount++; } }
auto已经不是原来那个auto了.早期是声明具有局部生存期的变量,只是个摆设,几乎无人使用。从C++11开始则是从声明初始化表达式中推导出变量类型,简化代码。
5 函数指针
int nCount = 0; void Function(int nElement){ if (nElement>5) { nCount++; }} std::for_each(vecCollection.begin(),vecCollection.end(), Function);
6 函数对象
class CFunctor{public: explicit CFunctor(int&nCount) :m_nCount(nCount) { } void operator()(int nElement) const { if(nElement>5) { m_nCount++; } }private: CFunctor&operator=(constCFunctor&); int& m_nCount;}; int nCount = 0; std::for_each(vecCollection.begin(),vecCollection.end(), CFunctor(nCount));
7 lambda
int nCount = 0; std::for_each(vecCollection.begin(),vecCollection.end(),[&nCount](int nElement) { if(nElement > 5) { nCount++; } });
8 全是STL
int nCount=std::count_if(vecCollection.begin(),vecCollection.end(),std::bind2nd(std::greater<int>(),5));
9 for each
int nCount = 0;for each(auto i in vecCollection){if (i>5){nCount++;}}
10 C++11
int nCount = 0;for (auto v : vecCollection){if (v > 5){nCount++;}}
0 0
- C++编程 - 回字有四样写法,你知道么?
- 天天 Java、C/C++,可这五种编程语言你知道吗?
- 你以前不知道有趣的C编程技巧
- c = f1() + f2()求值顺序你知道么?
- C/C++编程细节(一)——你未必知道
- C语言编程之你不知道的事——回调函数
- 你知道javap么?
- 工作?你知道么?
- RFID你知道么?
- 翻译连载 | 附录 C:函数式编程函数库-《JavaScript轻量级函数式编程》 |《你不知道的JS》姊妹篇
- 你必须知道的编程语言分类
- 你不知道的编程技巧
- 你不知道的编程技巧
- mapreduce编程模型你知道多少?
- 你知道几种编程思想?
- 你有必要知道的函数式编程
- 关于Socket编程你应该知道的
- #在C中的妙用你知道多少
- 从输入网址到显示网页的全过程分析
- Altium 设置 PCB Snap Component
- 产品岗位细分的一些思考
- 阿里_一道备受关注的前端开发笔试题
- Ubuntu U盘启动制作
- C++编程 - 回字有四样写法,你知道么?
- 采用gSOAP开发包开发 SOAPServer 和 SOAPClient 的简单示例
- Lucas定理相关证明
- 《Metaphor Interpretation and Context-based Affect Detection》读书笔记
- leetcode做题思路(一)
- 联合国安理会法院命令日本停止捕杀鲸鱼
- Hadoop自定义排序和自定义数据类型使用(setSortComparatorClass和setGroupingComparatorClass)
- dbus 信号和方法测试
- Java性能优化系列之二--程序优化