Open In App

How to Sort a Vector in a Map in C++?

In C++, we can create a map container where the values associated with keys is a vector. In this article, we will learn how to sort a vector within a map in C++.

Example



Input:
myMap = { {3, {9, 7, 3}},
{5, {4, 2, 8, 1, 6}}, {8, {1, 2, 5, 8}} }; Output: Map: Key: 3, Sorted Vector: [3 7 9 ] Key: 5, Sorted Vector: [1 2 4 6 8 ] Key: 8, Sorted Vector: [1 2 5 8 ]

Sort Vector in Map of Vectors in C++

To sort vectors in a map of vectors, we can directly use the std::sort() algorithm. We first iterator over the map to access each pair. In each pair, we go to the second element (which is vector) and then apply the sort algorithm on it using its iterators. We keep doing it till we reach the end of the map.

C++ Program to Sort Vector in Map




// C++ Program to Sort Vectors Inside a Map
  
#include <algorithm>
#include <iostream>
#include <map>
#include <vector>
using namespace std;
  
int main()
{
    // Declare a map with integer keys and vector of
    // integers as values
    map<int, vector<int> > sortedMap;
  
    // Assign vectors to map keys
    sortedMap[5] = { 4, 2, 8, 1, 6 };
    sortedMap[3] = { 9, 7, 3 };
    sortedMap[8] = { 5, 2, 1, 8 };
  
    // Sort vectors inside the map
    for (auto& tempPair : sortedMap) {
        sort(tempPair.second.begin(),
             tempPair.second.end());
    }
  
    // Display the sorted map
    cout << "Sorted Map:" << endl;
    for (const auto& pair : sortedMap) {
        cout << "Key: " << pair.first
             << ", Sorted Vector: [";
        for (const auto& element : pair.second) {
            cout << element << " ";
        }
        cout << "]" << endl;
    }
  
    return 0;
}

Output

Sorted Map:
Key: 3, Sorted Vector: [3 7 9 ]
Key: 5, Sorted Vector: [1 2 4 6 8 ]
Key: 8, Sorted Vector: [1 2 5 8 ]

Time Complexity: O(M * N * logN), where M is the number of vectors, and N is the average number of elements in the vector.
Space Complexity: (logN)


Article Tags :