Jul 10, 2010

Standard Template Library - pair

The pair class template declared in <utility> is provided to treat two values as a single unit. STL container classes map and multimap use pairs to manage their elements which are key/value pairs

The example code below demonstrates some of the ways of using a pair class and the convenience function make_pair()

#include <utility>
#include <iostream>
#include <string>
#include <map>

using namespace std;

void print_pair(pair<long, string> pr)
{
    cout << "[";
    cout << pr.first;
    cout << "]";
    cout << "=";
    cout << pr.second;
    cout << endl;
}


// Example: simple pair example
void simple_pair_example()
{
    pair<long, string> pr(1, "Simple Pair");
    print_pair(pr);
    cout << endl;
}

// Example: pointer to a pair
void pair_pointer_example()
{
    pair<long, string> *pr = new pair<long, string>(1, "Pointer Pair");
    print_pair(*pr);
    cout << endl;
    delete pr;
    pr = NULL;
}


// Example: pair and a map
void pair_map_example()
{
    map<long, string>   employees;

    employees[1] = "Employee1";
    employees[2] = "Employee2";
    employees[3] = "Employee3";
    employees[4] = "Employee4";

    map<long, string>::const_iterator it;
    for(it = employees.begin(); it != employees.end(); ++it)
    {
        print_pair(*it);
    }
    cout << endl;
}


// Example: pair and map find function
void pair_map_search()
{
    string user = "george";
    map<string, pair<string, string> >   employees;

    employees["pankaj"] = make_pair("Pankaj", "Tiwari");
    employees["paresh"] = make_pair("Paresh", "Tiwari");
    employees["george"] = make_pair("George", "Bush");

    map<string, pair<string, string> >::const_iterator it;
    if((it = employees.find(user)) == employees.end())
    {
        cerr << "Unknown User: " << user;
    }
    else
    {
        const pair<string, string> user = it->second;
        cout << user.first << user.second;
    }
    cout << endl;
}

int main()
{
    simple_pair_example();
    pair_pointer_example();
    pair_map_example();
    pair_map_search();
}


Program Output:

No comments :

Post a Comment