Friday, 2 September 2016

Learning STL in C++ -- 1.) Pair

Hello friends
     These  days I spent  my time learning about STL (Standard Templae Library) in C++ .
Actually STL is  a software library in C++ .It has  mainly four components  namely , Algorithms , Functional , Containers , Iterators .
Out  of  which , I found  Algorithms  and Containers very useful and am still learning them.
C++ STL is very vast and very very  useful and  user friendly .

First of  All I  would  like  to tell you about Containers .
They are the Objects that store data. The standard Sequence  Containers include : Vector , Deque , Stack, List
The standard associative Containers are Set , Multiset , Map
There are  also other Containers like Pair , hash_set etc.

1.) Pair : It is a simple associative container  which can store two  types  of  data together . These two types  of  data are called as 'first' and 'second' respectively  .
To use pair and its methods we include utility library .

Here is an Example  showing basic  usage of pair in c++ :



#include <iostream>
#include <utility>
using namespace std;
int  main()
{
    int  n = 1;
    int a[5] = {1, 2, 3, 4, 5};

    // build a pair from two ints
    pair<int,int> p1 = std::make_pair(n, a[1]);
    std::cout << "The value of p1 is "
              << "(" << p1.first << ", " << p1.second << ")\n";
}
we can  use  any two  different  data types to  store in pair .

Pair has many uses in other containers , that i will explain later .

Meanwhile there is an important keyword named auto  in C++ 11 and onwards  Go through This link  to  know  about  it . Its very useful in certain cases .




No comments:

Post a Comment