Monday, 27 July 2009

Example of C++ STL 'pair' container

The pair container is a rather basic container. It can be used to store two elements, called first and second, and that's about it. To define a variable as a pair container, the header file must be included. 'pair' can do basic features like assignment and comparisons and has no further special features. It is, however, a basic ingredient of the abstract containers map, multimap and hash_map.

Lets look at the example now:

//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//A simple example of C++ STL container 'pair'

using namespace


pair<string, string> name("Zahid","Ghadialy"); //firstname, lastname
string custName = name.first+" "+name.second;
pair<string, int> customerNum(custName, 23456); //firstname, cust. no.
pair<int, int> customerAge(customerNum.second, 30); //cust. no., age

cout<<"Customer Full Name = "<<custName<<endl;
cout<<"Customer Number of "<<customerNum.first<<" is "<<customerNum.second<<endl;
cout<<"Age of Customer Number = "<<customerAge.first<<" is "<<customerAge.second<<endl;

//If we now want to increment say, age by 1
cout<<"New age of Customer Number = "<<customerAge.first<<" is "<<customerAge.second<<endl;


The output is as follows:

No comments:

Post a Comment