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++; } }