C++ STL中的常用遍歷算法分享
1.for_each
功能描述
實現(xiàn)容器遍歷
函數(shù)原型
for_each(itertor beg,iterator end,_func);
//遍歷算法 遍歷容器元素
//beg 開始迭代器
//end 結束迭代器
//_func函數(shù)或者函數(shù)對象
代碼
#include <iostream> using namespace std; #include <vector> #include <algorithm> //普通函數(shù) void print01 (int val) { cout<< val << " "; } //放寒暑 class print02 { public: void operator()(int val) { cout<< val << " "; } }; void test01() { vector<int>v; for(int i = 0;i < 10;i ++) { v.push_back(i); } for_each(v.begin(),v.end(),print01); cout<<endl; for_each(v.begin(),v.end(),print02()); cout<<endl; } int main() { test01(); }
運行結果
2.transform
功能描述
搬運容器到另一個容器
函數(shù)原型
transform (iterator beg1,iterator endl, iterator beg2,_func);
//beg1 源容器開始迭代器
//end1 源容器結束迭代器
//beg2 目標函數(shù)開始迭代器
//_func 函數(shù)或者函數(shù)對象
代碼
#include <iostream> using namespace std; #include <vector> #include <algorithm> class Transform { public: int operator()(int v) { return v; } }; class MyPrint{ public: void operator()(int val) { cout<< val <<" "; } }; void test01() { vector<int>v; for(int i = 0;i < 10;i ++) { v.push_back(i); } vector<int>vTarget; //目標函數(shù) vTarget.resize(v.size()); //目標容器要提前開辟空間 transform(v.begin(), v.end(), vTarget.begin(),Transform()); for_each(vTarget.begin(),vTarget.end(), MyPrint()); cout<<endl; } int main() { test01(); }
運行結果
到此這篇關于C++ STL中的常用遍歷算法分享的文章就介紹到這了,更多相關C++ STL遍歷算法內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
VS2019開發(fā)簡單的C/C++動態(tài)鏈接庫并進行調(diào)用的實現(xiàn)
這篇文章主要介紹了VS2019開發(fā)簡單的C/C++動態(tài)鏈接庫并進行調(diào)用的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-03-03