Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Even though correct answers have already been posted, I thought I'd add a demo of how you can do this cleanly:</p> <pre><code>template&lt;typename A, typename B&gt; std::pair&lt;B,A&gt; flip_pair(const std::pair&lt;A,B&gt; &amp;p) { return std::pair&lt;B,A&gt;(p.second, p.first); } template&lt;typename A, typename B&gt; std::multimap&lt;B,A&gt; flip_map(const std::map&lt;A,B&gt; &amp;src) { std::multimap&lt;B,A&gt; dst; std::transform(src.begin(), src.end(), std::inserter(dst, dst.begin()), flip_pair&lt;A,B&gt;); return dst; } int main(void) { std::map&lt;int, double&gt; src; ... std::multimap&lt;double, int&gt; dst = flip_map(src); // dst is now sorted by what used to be the value in src! } </code></pre> <hr> <p><strong>Generic Associative Source (requires C++11)</strong></p> <p>If you're using an alternate to <code>std::map</code> for the source associative container (such as <code>std::unordered_map</code>), you could code a separate overload, but in the end the action is still the same, so a generalized associative container using variadic templates can be used for <em>either</em> mapping construct:</p> <pre><code>// flips an associative container of A,B pairs to B,A pairs template&lt;typename A, typename B, template&lt;class,class,class...&gt; class M, class... Args&gt; std::multimap&lt;B,A&gt; flip_map(const M&lt;A,B,Args...&gt; &amp;src) { std::multimap&lt;B,A&gt; dst; std::transform(src.begin(), src.end(), std::inserter(dst, dst.begin()), flip_pair&lt;A,B&gt;); return dst; } </code></pre> <p>This will work for both <code>std::map</code> and <code>std::unordered_map</code> as the source of the flip.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload