1

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!!!

nelt22
  • 410
  • 1
  • 5
  • 13
  • See this possible duplicate: [create an own comparator for map](http://stackoverflow.com/questions/5733254/create-an-own-comparator-for-map). The comparator determines the order of the elements. You need `p` to be less than `e` and `e` less than `r`. – juanchopanza Mar 19 '14 at 19:35

1 Answers1

2

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;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335