c++ STL常用遍歷算法
更新時間:2020年12月17日 11:17:27 作者:西西嘛呦
這篇文章主要介紹了c++ STL常用遍歷算法的實現(xiàn),幫助大家更好的理解和使用c++,感興趣的朋友可以了解下
需要引入頭文件#include<algorithm>
1.for_each
#include<iostream> using namespace std; #include <vector> #include <algorithm> class MyPrint { public: void operator()(int val) const{ cout << val << " "; } }; void printVector(int val) { cout << val << " "; } void test() { vector<int> v1; for (int i = 0; i < 10; i++) { v1.push_back(i); } //利用普通函數(shù) for_each(v1.begin(), v1.end(), printVector); cout << endl; //利用仿函數(shù) for_each(v1.begin(), v1.end(), MyPrint()); cout << endl; } int main() { test(); system("pause"); return 0; }
2.transform:將容器搬運到另一個容器中
#include<iostream> using namespace std; #include <vector> #include <algorithm> class Transform { public: int operator()(int val) const{ //這里可以對val進行一些判斷 return val; } }; class MyPrint { public: void operator()(int val) const { cout << val << " "; } }; void test() { vector<int> v1; for (int i = 0; i < 10; i++) { v1.push_back(i); } vector<int> v2; //目標容器需要先開辟空間 v2.resize(v1.size()); transform(v1.begin(), v1.end(), v2.begin(), Transform()); for_each(v2.begin(), v2.end(), MyPrint()); cout << endl; } int main() { test(); system("pause"); return 0; }
以上就是c++ STL常用遍歷算法的詳細內(nèi)容,更多關(guān)于c++ 遍歷算法的資料請關(guān)注腳本之家其它相關(guān)文章!
您可能感興趣的文章:
- C++之string類對象的容量操作詳解
- C++ stringstream類用法詳解
- C++string容器基本概念詳解
- 深入探究C++ string的內(nèi)部究竟是什么樣的
- C++ string字符串的修改與替換方法詳析
- c++ string的erase刪除方法
- C++ 字符串string和整數(shù)int的互相轉(zhuǎn)化操作
- C++中string轉(zhuǎn)換為char*類型返回后亂碼問題解決
- C++中string替換所有指定字符串的方法
- C++ string格式化輸出方式
- C++ string替換指定字符實例代碼
- C++ STL中常見的算法使用方式
- C++ STL 序列式容器與配接器的簡單使用
- 關(guān)于C++STL string類的介紹及模擬實現(xiàn)
相關(guān)文章
Qt多線程實現(xiàn)網(wǎng)絡(luò)發(fā)送文件功能
這篇文章主要為大家詳細介紹了Qt多線程實現(xiàn)網(wǎng)絡(luò)發(fā)送文件功能,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-08-08C/C++雜記 虛函數(shù)的實現(xiàn)的基本原理(圖文)
這篇文章主要介紹了C/C++雜記 虛函數(shù)的實現(xiàn)的基本原理(圖文),需要的朋友可以參考下2016-06-06