C++ //STL---常用算法 //常用遍历 for_each //transform
1 //STL---常用算法 2 //常用遍历 for_each 3 //transform 4 #include<iostream> 5 #include<string> 6 #include<functional> 7 #include<algorithm> 8 #include<vector> 9 10 //using namespace std; 11 using namespace std; 12 //普通函数 13 void print01(int val) 14 { 15 cout << val << " "; 16 } 17 18 //仿函数 19 class print02 20 { 21 public: 22 void operator()(int val) 23 { 24 cout << val << " "; 25 } 26 }; 27 28 29 void test01() 30 { 31 vector<int>v; 32 for (int i = 0; i < 10; i++) 33 { 34 v.push_back(i); 35 } 36 37 for_each(v.begin(), v.end(), print01); 38 cout << endl; 39 40 for_each(v.begin(), v.end(), print02()); 41 cout << endl; 42 } 43 44 //transform 45 //搬运的 46 class Transform 47 { 48 public: 49 int operator()(int v) 50 { 51 return v + 100; 52 } 53 }; 54 55 //void print03(int vT) 56 //{ 57 // cout << vT << " "; 58 //} 59 class print03 60 { 61 public: 62 void operator()(int val) 63 { 64 cout << val << " "; 65 } 66 }; 67 68 69 void test02() 70 { 71 vector<int>v; 72 for (int i = 0; i < 10; i++) 73 { 74 v.push_back(i); 75 } 76 cout << "v容器数据:" << endl; 77 78 for_each(v.begin(), v.end(), print03()); 79 cout << endl; 80 81 //cout << "v容器数据:" << endl; 82 //for (vector<int>::iterator it = v.begin(); it != v.end(); it++) 83 //{ 84 // cout << *it << " "; 85 //} 86 //cout << endl; 87 88 89 vector<int>vTarget; //目标容器 90 vTarget.resize(v.size()); //目标容器需要提前开辟空间 91 92 transform(v.begin(), v.end(), vTarget.begin(), Transform()); 93 94 cout << "vTarget容器数据:" << endl; 95 for_each(vTarget.begin(), vTarget.end(), print03()); 96 cout << endl; 97 } 98 int main() 99 { 100 //test01(); 101 test02(); 102 system("pause"); 103 return 0; 104 }
本文来自博客园,作者:Bytezero!,转载请注明原文链接:https://www.cnblogs.com/Bytezero/p/15151362.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)