 <p>If your compiler supports C++ 2011 then you can write the following way providing that letters will be listed in the order in which they are present in the string</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; #include &lt;map&gt; int main() { std::string s( "slowly" ); auto comp = [&amp;]( char c1, char c2 ) { return s.find( c1 ) &lt; s.find( c2 ); }; std::map&lt;char, int, decltype( comp )&gt; m( comp ); for ( char c : s ) ++m[c]; for ( auto p : m ) std::cout &lt;&lt; p.first &lt;&lt; ": " &lt;&lt; p.second &lt;&lt; std::endl; } </code></pre> <p>The program output is</p> <pre><code>s: 1 l: 2 o: 1 w: 1 y: 1 </code></pre> <p>Otherwise if the compiler does not support C++ 2011 then instead of the lambda you have to use a function class defined before main. Also youi should substitute the range-based for loop for an ordinary loop.</p>