jeudi 2 mars 2017

Making this C++ code cleaner and more succinct

I have been a python developer for a few years and I'm going through some simple exercises to learn C++.

Please consider the following python snippet

# Find the most frequent integer in an array
lst = [1,2,4,3,1,3,1,4,5,15,5,2,3,5,4]
mydict   = {}
cnt, itm = 0, ''

for item in lst:
     mydict[item] = mydict.get(item, 0) + 1
     if mydict[item] >= cnt :
         cnt, itm = mydict[item], item

print(itm)

It may not be very clean and it misses elements that tie for most frequent, but it is succinct code. I re-wrote this to C++11 as:

#include <iostream>
#include <unordered_map>
#include <string>

int main(int argc, char const *argv[])
{
    using std::cout;

    int foo [] = {1,2,4,3,1,3,1,4,5,15,5,2,3,5,4};

    std::unordered_map<std::string, int> dict;

    std::string item;

    int count = 0;

    std::string itm;

    for (int i : foo) {
        item = std::to_string(i);

        auto it = dict.find(item);

        if (it != dict.end()) {
            it->second = it->second++;

            if (it->second >= count) {
                count = it->second;
                itm = item;
            }
        } else {
            dict.insert(std::make_pair<std::string, int>(item, 0));
        }

    }

    std::cout << "The integer most frequent is " << itm << "\n";
    return 0;
}

This executes fine and returns 4 which is one of the correct answers. Can someone please offer a re-write of this to make it more succinct.

At present I am not concerned about if there's more than one element in the list that has a tie for most frequent. I am more concerned with cleaner code.

Aucun commentaire:

Enregistrer un commentaire