diff --git a/Sorting a Map by value in C++ b/Sorting a Map by value in C++ new file mode 100644 index 0000000..daa4558 --- /dev/null +++ b/Sorting a Map by value in C++ @@ -0,0 +1,54 @@ +// C++ program for the above approach + +#include +using namespace std; + +// Comparator function to sort pairs +// according to second value +bool cmp(pair& a, + pair& b) +{ + return a.second < b.second; +} + +// Function to sort the map according +// to value in a (key-value) pairs +void sort(map& M) +{ + + // Declare vector of pairs + vector > A; + + // Copy key-value pair from Map + // to vector of pairs + for (auto& it : M) { + A.push_back(it); + } + + // Sort using comparator function + sort(A.begin(), A.end(), cmp); + + // Print the sorted value + for (auto& it : A) { + + cout << it.first << ' ' + << it.second << endl; + } +} + +// Driver Code +int main() +{ + + // Declare Map + map M; + + // Given Map + M = { { "GfG", 3 }, + { "To", 2 }, + { "Welcome", 1 } }; + + // Function Call + sort(M); + return 0; +}