pair utility classThe pair template class is defined in <utility> to keep pairs of values.
Aside from some functions that return two values in a pair, the elements of a
map are stored as key-value pairs. The following illustrates the declaration
and use of pair, with it's two public fields, first and second.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
// map/pair-test.cpp - Show basic use of pair.
// 2004-02-29 - Fred Swartz - Rodenbach
#include <utility>
#include <iostream>
#include <string>
#include <map>
using namespace std;
int main() {
//-- Declare a pair variable.
pair<string, int> pr1;
//-- Declare and initialize with constructor.
pair<string, int> pr2("heaven", 7);
cout << pr2.first << "=" << pr2.second << endl;
// Prints heaven=7
//-- Declare and initialize pair pointer.
pair<string, int>* prp = new pair<string, int>("yards", 9);
cout << prp->first << "=" << prp->second << endl;
// Prints yards=9
//-- Declare map and assign value to keys.
map<string, string> engGerDict;
engGerDict["shoe"] = "Schuh";
engGerDict["head"] = "Kopf";
//-- Iterate over map. Iterator value is a key-value pair.
// Iteration in map is in sorted order.
map<string, string>::const_iterator it;
for (it=engGerDict.begin(); it != engGerDict.end(); ++it) {
cout << it->first << "=" << it->second << endl;
}
// Prints head=kopf
// shoe=Schuh
system("PAUSE");
return 0;
}
|