nelt22
nelt22

Reputation: 410

Custom ordering of keys in map

I'm making an exercise where I'm traversing a word ("pepper") and I'm counting the times each character is repeated and I would like the output be:

p: 3
e: 2
r: 1

(sorted in order of appearance)

I'm using a map:

void foo(string word)
{
    map<char, int> m;
    for(int i = 0; i < word.length(); i++)
    m[word[i]]++;

    map<char, int>::iterator myIt;
    for(myIt = m.begin(); myIt != m.end(); myIt++)
        cout << myIt->first << ": " << myIt->second << endl;
}

The problem here is the order of the output:

e: 2
p: 3
r: 1

I would like it to be as I mentioned earlier. Is there any way to modify the way the map orders the values it stores?

Cheers!!!

Upvotes: 1

Views: 124

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 310990

I only tested the code below with MS VC++ 2010.

void foo( const std::string &word )
{
    auto order = [&]( char x, char y )
    {
        return ( word.find( x ) < word.find( y ) );
    };

    std::map<char, int, decltype( order )> m( order );
    for ( char c : word ) ++m[c];

    for ( const auto &p : m ) std::cout << p.first << ": " << p.second << std::endl;
    std::cout << std::endl;
}

Upvotes: 2

Related Questions