Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>As andre said, to avoiding overloading operators on your struct you can use the following map:</p> <p><code>std::map&lt;std::pair&lt;int, int&gt;, int&gt; a_map;</code></p> <p><strong>Insertion:</strong></p> <p>Insert into it with <code>a_map.insert(std::pair&lt;std::pair&lt;int,int&gt;, int&gt;(std::pair&lt;int,int&gt;(x, y), z));</code></p> <p>or</p> <p><code>std::pair&lt;int, int&gt; index(x, y); a_map[index] = z;</code></p> <p>or (neatest version, borrowed from andre's answer)</p> <p><code>a_map[make_pair(x, y)] = z;</code></p> <p><strong>Access:</strong></p> <p>If you're only iterating through the elements and don't particularly care about accessing values by their index very often this method is fine. If you <em>do</em> want to do that then you can access them like so:</p> <p><code>std::pair&lt;int, int&gt; index(x, y); int z = a_map[index];</code></p> <p>or (neatest version)</p> <p><code>int z = a_map[make_pair(x, y)];</code></p> <p>You could also use <code>find()</code> but once again, you'll need to construct a <code>pair</code> for it (<a href="http://www.cplusplus.com/reference/map/map/find/" rel="nofollow">http://www.cplusplus.com/reference/map/map/find/</a>).</p> <p>You can use the <code>make_pair()</code> function from <code>&lt;utility&gt;</code> (<a href="http://www.cplusplus.com/reference/utility/make_pair/" rel="nofollow">http://www.cplusplus.com/reference/utility/make_pair/</a>) to make constructing the pairs a bit easier but if you don't want to use a map with pairs as the indexes then you might want to revert to the original plan and use an <code>std::map&lt;pos, int&gt;</code> instead. </p> <p><strong>Alternative map:</strong></p> <p>If you decide to use <code>std::map&lt;pos, int&gt;</code> just remember to overload <code>operator&lt;</code> on <code>pos</code> to allow your <code>map</code> to sort its keys (since you aren't actually making any use of the sorting feature, you can return the comparison of either <code>pos::x</code> or <code>pos::y</code> arbitrarily).</p> <p><strong>Unordered map:</strong></p> <p>If you want to avoid the need to overload the operator and the sorting entirely, you can use the new C++11 <code>unordered_map</code> which is a more efficient container for insertions and deletions anyway. Since you're only using the uniqueness and iterator properties of <code>map</code>, it would be worth considering using <code>unordered_map</code> if you can (they have very similar interfaces and I've used them in place of <code>map</code> just by changing the type of my variable before!) </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