We have seen sequential iner works with copy () algorithm. As long as a program is running, all values can be exported to cout. Map associative container cannot use this trick, is there any other solution?
Map is an associative container because it is a struct value. If copy () is used to get cout, cout will be dumpfounded. If you don't know how to capture a value, you can certainly use for loop, however, based on the use of STL, we use for_each () algorithm instead of for/while loop.
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) {
30Cout<P. Second<Endl;
31}
Results
1 Stanley B. Lippman
2 Scott Meyers
3 Andrei Alexandrescu
4 Please press any extra parameter...
The trigger when using for_each () is not as shocking as copy (), but at least many programs are running.