6 Lines concise C++ (STL functional programming style)

  • 5

    I personally like to heavily use STL and C++ functional programming. Not saying this is the coding style good for all people, just want to show another C++ programming style. It's easy to write concise code with this style, but sometimes it may look awkward to people unfamiliar with it.

    class Solution {
            vector<int> topKFrequent(vector<int>& nums, int k) {
                unordered_map<int, int> my_map;
                for_each (begin(nums), end(nums), [&my_map](int i){ my_map[i]++;});
                vector<pair<int, int>> pv(begin(my_map), end(my_map));
                nth_element(begin(pv), begin(pv)+k, end(pv), [](pair<int, int> a, pair<int, int> b){return a.second > b.second;});
                vector<int> result;
                transform(begin(pv), begin(pv)+k, back_inserter(result), [](pair<int, int> a){return a.first;});
                return result;

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.