將map輸出到cout,是否有更方便的方法? (C/C++) (STL)

來源:互聯網
上載者:User

大家都體會過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<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
29void print(pair<int, string> p) {
30  cout << p.second << endl;
31}

執行結果

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

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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.