李sir_Blog

博客园 首页 联系 订阅 管理
  705 随笔 :: 58 文章 :: 134 评论 :: 193万 阅读

大家都體會過sequential container搭配copy() algorithm,只要一行程式就可以將所有值輸出到cout,map這種associative container就無法用這一招,是否有其它方式解決呢?

map這種associative container因為是雙值,若用copy()到cout,會讓cout傻眼,不知道要抓拿一個值,當然用for loop一定可以,但基於使用STL的最高境界:不用for/while loop,此範例我們使用了for_each() algorithm。

 1/* 
 2(C) OOMusou 2006 http://oomusou.cnblogs.com
 3
 4Filename    : MapWithfor_each.cpp
 5Compiler    : Visual C++ 8.0 / ISO C++
 6Description : Demo how to use for_each() algorithm to print map.
 7Release     : 12/14/2006 1.0
 8*/

 9#include <iostream>
10#include <map>
11#include <algorithm>
12#include <string>
13
14using namespace std;
15
16void print(pair<int,string>);
17
18int main() {
19  map<intstring> authors;
20  authors[1= "Stanley B. Lippman";
21  authors[2= "Scott Meyers";
22  authors[3= "Andrei Alexandrescu";
23
24  for_each(authors.begin(), authors.end(), print);
25
26  return 0;
27}

28
29void print(pair<intstring> p) {
30  cout << p.second << endl;
31}


執行結果

1Stanley B. Lippman
2Scott Meyers
3Andrei Alexandrescu
4請按任意鍵繼續 . . .


使用for_each()的感動雖然不如copy()那樣震撼,但最少程式乾淨了許多。

posted on   李sir  阅读(515)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示