Skip to content
Related Articles

Related Articles

Vector of Maps in C++ with Examples

Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 28 Jul, 2022
Improve Article
Save Article

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




// C++ program to demonstrate the use
// of vector of maps
#include <bits/stdc++.h>
using namespace std;
 
// Function to count frequency
// up to each index
void findOccurrences(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
    findOccurrences(S);
 
    return 0;
}

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

 


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!