title: Is there a way to implement this using transform instead of for_each? If yes, is it actually better to do so?
body: <p>Given a string s, how can I use transform to create an unordered_map that contains the number of times each character was encountered? Is it worth the bother?</p>
  
  <p>My initial thought was to use transform, but I wasn't sure how to implement the "increment value if exists, else add" part. I ended up using for_each instead.</p>
  
  <p>Using for_each:</p>
  
  <pre><code>unordered_map&lt;char, int&gt; charMap;
  for_each(begin(s), end(s), [&amp;charMap](char c){charMap[c]++;});
  </code></pre>
  
  <p>I was hoping to be able to do something like this, but for map instead of multimap:</p>
  
  <pre><code>unordered_multimap&lt;char, int&gt; charMap2;
  transform(begin(s), end(s), inserter(charMap2, begin(charMap2)), [&amp;](char c){
          return make_pair(c, 1);
          });
  </code></pre>
  
  <p>UPDATE:
  See @patatahooligan's comment for why, although hackable enough to make it work, transform (intended for 1-to-1 transformations) might not be best suited here. 
  See Maxim's (accepted) answer for more suitable strategies. </p>