In this C++ tutorial, you shall learn how to convert a given vector into a map of entries with unique values of vector elements as keys, and their number of occurrences as values, with example programs.
Convert Vector to Map
To convert vector to map in C++, where entries in the map are formed with the elements of vector as keys and their number of occurrences as values, iterate over the elements of the vector and insert them as an entry into map if there is no such key already present, or increment the value of map-entry if the key is already present.
C++ Program
In the following program, we take a string vector in fruits
, and convert this into a map with elements of the vector as keys, and their number of occurrences as respective values.
We use For Loop to iterate over the elements of the vector, If-else statement to check if the key is already present, and increment operator to increment the entry’s value.
main.cpp
#include <iostream>
#include <vector>
#include <map>
using namespace std;
int main() {
vector<string> v { "apple", "banana", "apple", "cherry", "cherry" };
map<string, int> m;
for( auto& element: v ) {
if ( m.count(element) ) {
m[element]++;
} else {
m[element] = 1;
}
}
for(auto& entry: m) {
cout << entry.first << " - " << entry.second << endl;
}
}
Output
apple - 2
banana - 1
cherry - 2
Conclusion
In this C++ Tutorial, we learned how to convert a vector into a map of entries with unique values of vector elements as keys, and their number of occurrences as values.