diff --git a/sort_map_by_value_ascending.cpp b/sort_map_by_value_ascending.cpp new file mode 100644 index 0000000..9081911 --- /dev/null +++ b/sort_map_by_value_ascending.cpp @@ -0,0 +1,32 @@ +#include +#include +#include +#include +#include + +int main() +{ + + // Creating & Initializing a map of String & Ints + std::map mapOfWordCount = { { "a", 10 }, { "b", 41 }, { "c", 62 }, { "d", 13 } }; + + // Declaring the type of Predicate that accepts 2 pairs and return a bool + typedef std::function, std::pair)> Comparator; + + // Defining a lambda function to compare two pairs. It will compare two pairs using second field + Comparator compFunctor = + [](std::pair element1 ,std::pair element2) + { + return element1.second < element2.second; + }; + + // Declaring a set that will store the pairs using above comparision logic + std::set, Comparator> setOfWords(mapOfWordCount.begin(), mapOfWordCount.end(), compFunctor); + + // Iterate over a set + // It will display the items in sorted order of values + for (std::pair element : setOfWords) + std::cout << element.first << " :: " << element.second << std::endl; + + return 0; +}