將map輸出到cout,是否有更方便的方法? (C/C++) (STL)
时间:2010-10-27 来源:李sir
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
4
Filename : MapWithfor_each.cpp
5
Compiler : Visual C++ 8.0 / ISO C++
6
Description : Demo how to use for_each() algorithm to print map.
7
Release : 12/14/2006 1.0
8
*/
9
#include <iostream>
10
#include <map>
11
#include <algorithm>
12
#include <string>
13
14
using namespace std;
15
16
void print(pair<int,string>);
17
18
int main()
{
19
map<int, string> 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
29
void print(pair<int, string> p)
{
30
cout << p.second << endl;
31
}
/**//* 2
(C) OOMusou 2006 http://oomusou.cnblogs.com3

4
Filename : MapWithfor_each.cpp5
Compiler : Visual C++ 8.0 / ISO C++6
Description : Demo how to use for_each() algorithm to print map.7
Release : 12/14/2006 1.08
*/9
#include <iostream>10
#include <map>11
#include <algorithm>12
#include <string>13

14
using namespace std;15

16
void print(pair<int,string>);17

18
int main()
{19
map<int, string> 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

29
void print(pair<int, string> p)
{30
cout << p.second << endl;31
}
執行結果
1
Stanley B. Lippman
2
Scott Meyers
3
Andrei Alexandrescu
4
請按任意鍵繼續 . . .
Stanley B. Lippman2
Scott Meyers3
Andrei Alexandrescu4
請按任意鍵繼續 . . .
使用for_each()的感動雖然不如copy()那樣震撼,但最少程式乾淨了許多。
相关阅读 更多 +
排行榜 更多 +
/**//* 









