Skip to content
Related Articles

Related Articles

Vector of Maps in C++ with Examples
  • Last Updated : 18 Nov, 2020

Map in STL: Maps are associative containers that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have same key values.

Vector in STL: Vector is the same as dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container. Vector elements are placed in contiguous storage so that they can be accessed and traversed using iterators.

Vector of Maps in STL: Vector of maps can be used to design complex and efficient data structures.

Syntax:

Vector of Ordered Map:
vector<map<datatype, datatype> > VM;



Vector of Unordered map:
vector<unordered_map<datatype, datatype> > VUM;

Examples:
Given a string. The task is to find the frequency of characters up to each index.

C++14

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to demostrate the use
// of vector of maps
#include <bits/stdc++.h>
using namespace std;
  
// Function to count frequency
// up to each index
void findOccurences(string s)
{
    // Vector of map
    vector<map<char, int> > mp(s.length());
  
    // Traverse the string s
    for (int i = 0; i < s.length(); i++) {
  
        // Update the frequency
        for (int j = 0; j <= i; j++) {
            mp[i][s[j]]++;
        }
    }
  
    // Print the vector of map
    for (int i = 0; i < s.length(); i++) {
  
        cout << "Frequency upto "
             << "position " << i + 1
             << endl;
  
        // Traverse the map
        for (auto x : mp[i])
            cout << x.first << "-"
                 << x.second << endl;
    }
}
  
// Driver Code
int main()
{
    // Input string S
    string S = "geeks";
  
    // Function Call
    findOccurences(S);
  
    return 0;
}

chevron_right


Output:

Frequency upto position 1
g-1
Frequency upto position 2
e-1
g-1
Frequency upto position 3
e-2
g-1
Frequency upto position 4
e-2
g-1
k-1
Frequency upto position 5
e-2
g-1
k-1
s-1

Attention reader! Don’t stop learning now. Get hold of all the important C++ Foundation and STL concepts with the C++ Foundation and STL courses at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :