Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<blockquote> <p>Is there a way (e.g. some coding convention I could follow from now on) I could have prevented this from hurting me?</p> </blockquote> <p>This may sound snarky, but: by reading the documentation.</p> <p>Since what you did is somewhat <em>expected</em> behaviour of the map, there’s not much you can do to guard against it.</p> <p>One thing you <em>can</em> heed in the future is the following. In your second step, you did something wrong:</p> <blockquote> <p>Check the return value and if NULL use insert to insert a new element in the map.</p> </blockquote> <p>This does <strong>never</strong> work with C++ standard library functions (other than C compatibility functions and <code>new</code>): the standard library doesn’t deal in pointers, least of all null pointers, so checking against <code>NULL</code> (or <code>0</code> or <code>nullptr</code>) rarely makes sense. (Apart from that, it wouldn’t make sense for a map’s <code>operator []</code> to return a pointer in the first place. It <em>obvoiusly</em> returns the <em>element type</em> (or rather, a reference to it)).</p> <p>In fact, the standard library predominantly uses <em>iterators</em> so if at all, check for iterator validity by comparing against the <code>end()</code> of a container.</p> <p>Unfortunately, your code (checking against <code>NULL</code>) compiled since <code>NULL</code> is actually a macro that’s equal to <code>0</code> in C++ so you can compare it against an integer.</p> <p>C++11 gets safer by introducing the <code>nullptr</code> keyword which has a distinct type, so comparing it with an integer wouldn’t compile. So this is a useful coding convention: never use <code>NULL</code>, and instead compile with C++11 support enabled and use <code>nullptr</code>.</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