Thursday 11 May 2017

STL in CPP

At the core of the C++ Standard Template Library are following three well-structured components:
ComponentDescription
ContainersContainers are used to manage collections of objects of a certain kind. There are several different types of containers like deque, list, vector, map etc.
AlgorithmsAlgorithms act on containers. They provide the means by which you will perform initialization, sorting, searching, and transforming of the contents of containers.
IteratorsIterators are used to step through the elements of collections of objects. These collections may be containers or subsets of containers.
List stores elements at non contiguous memory location i.e. it internally uses a doubly linked list i.e.
So, insertion and deletion in list is much efficient than vector in c++.
 std::list<std::string> listOfStrs = { "First", "Sec",
                                "Third", "Fourth",
                                "Fifth", "Sixth"
                                };


Whereas, vector stores elements at contiguous memory locations like an array i.e.
 Therefore, in vector random access is possible i.e. we can directly access the 15th element in vector using operator []
std::vector<int> vec(20);
vec[15] = 10;

  
// create a vector to store int
   vector<int> vec; 
// display the original size of vec
   cout << "vector size = " << vec.size() << endl;

   // push 5 values into the vector
   for(i = 0; i < 5; i++){
      vec.push_back(i);
   }
// use iterator to access the values
   vector<int>::iterator v = vec.begin();
   while( v != vec.end()) {
      cout << "value of v = " << *v << endl;
      v++;
   }  
 

std::set

std::set is an associative container and header that need to be include for it is,

Benefits and Features of std::set:

  • It’s doesn’t allow duplicate elements i.e. it only contains unique elements.
  • Std::set can contain element of any specified type in template argument.     std::set<int> // contains only int elements.
       class Sample;
         std::set<Sample> // contains only Sample class objects. 
  • std::set internally store elements in balanced binary tree.
  • std::set will keep the inserted elements in sorted order based on the assigned sorting criteria
  • Output:
    first second third
    first second

    std::unordered_set

    all elements in the unordered_set are immutable i.e. they can not be modified once inserted

    unordered_set stores the elements internally using a Hash Table. 

    Output:

     

    std::map

    std::map is an associative container that store elements in key-value pair. 

    Benefits of using std::map :

  • It stores only unique keys and that too in sorted order based on its assigned sorting criteria.
  • As keys are in sorted order therefore searching element in map through key is very fast i.e. it takes logarithmic time.
  • In std::map there will be only one value attached with the every key.
    • It might be implemented using balanced binary trees.


    C++
    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
    #include <iostream>
    #include <map>
    #include <string>
    #include <iterator>
    int main()
    {
        std::map<std::string, int> mapOfWords;
        // Inserting data in std::map
        mapOfWords.insert(std::make_pair("earth", 1));
        mapOfWords.insert(std::make_pair("moon", 2));
        mapOfWords["sun"] = 3;
        // Will replace the value of already added key i.e. earth
        mapOfWords["earth"] = 4;
        // Iterate through all elements in std::map
        std::map<std::string, int>::iterator it = mapOfWords.begin();
        while(it != mapOfWords.end())
        {
            std::cout<<it->first<<" :: "<<it->second<<std::endl;
            it++;
        }
        // Check if insertion is successful or not
        if(mapOfWords.insert(std::make_pair("earth", 1)).second == false)
        {
            std::cout<<"Element with key 'earth' not inserted because already existed"<<std::endl;
        }
        // Searching element in std::map by key.
        if(mapOfWords.find("sun") != mapOfWords.end())
            std::cout<<"word 'sun' found"<<std::endl;
        if(mapOfWords.find("mars") == mapOfWords.end())
            std::cout<<"word 'mars' not found"<<std::endl;
        return 0;
    }
     

    multimap

    Multi-map in C++ is an associative container like map. It internally store elements in key value pair. But unlike map which store only unique keys, multimap can have duplicate keys.

    #include <map>
    #include <iterator>
    #include <algorithm>
    int main()
    {
    //Multi Map of char and int
    // Initializing with initializer list
    std::multimap<char, int> mmapOfPos ={
    {'t', 1},
    {'h', 1},
    {'i', 2},
    {'s', 3},
    {'i', 5},
    {'s', 6},
    {'i', 8},
    };
    // Inserting an element in map
    mmapOfPos.insert(std::pair<char, int>('t', 9));
    // Iterate over the multimap using Iterator
    for (std::multimap<char, int>::iterator it = mmapOfPos.begin();
    it != mmapOfPos.end(); it++)
    std::cout << it->first << " :: " << it->second << std::endl;
    std::cout << "****************************************" << std::endl;
    // Iterate over the multimap using range based for loop
    for (std::pair<char, int> elem : mmapOfPos)
    std::cout << elem.first << " :: " << elem.second << std::endl;
    return 0;
    }
    Output:
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    h :: 1
    i :: 2
    i :: 5
    i :: 8
    s :: 3
    s :: 6
    t :: 1
    t :: 9
    ****************************************
    h :: 1
    i :: 2
    i :: 5
    i :: 8
    s :: 3
    s :: 6
    t :: 1
    t :: 9

     

    std::deque

    Deque is a double ended queue container that provides insertion and deletion at both ends i.e. front and back with
    high performance unlike vector that provides high performance insertion at end i.e. back only.

    Also it provides random access to elements just like a vector.

     

    Output is as follows,
    5 6
    3 4 5 6
    3 4 5
    4 5

     

No comments:

Post a Comment