Vector of Maps in C++ with Examples
Last Updated :
28 Jul, 2022
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
#include <bits/stdc++.h>
using namespace std;
void findOccurrences(string s)
{
vector<map< char , int > > mp(s.length());
for ( int i = 0; i < s.length(); i++) {
for ( int j = 0; j <= i; j++) {
mp[i][s[j]]++;
}
}
for ( int i = 0; i < s.length(); i++) {
cout << "Frequency upto "
<< "position " << i + 1
<< endl;
for ( auto x : mp[i])
cout << x.first << "-"
<< x.second << endl;
}
}
int main()
{
string S = "geeks" ;
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
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...