Does this code work across all standard compliant C++ compilers (it works with g++)? Why (please give c++11 reference, if possible)? How about std::unordered_map and associative containers in general?
std::map<std::string, std::string> map;
std::map<std::string, std::string>::iterator i(map.end());
map.insert({"bla", ""});
map.insert({"hah", ""});
assert(map.end() == i);
For map, yes — virtually nothing but deletion of the referred-to object invalidates an iterator in a map.
For unordered_map, in practice, maybe yes for this specific case — the
enditerator is often a bit different from other iterators, so it may not contain any actual address or anything like that — it’s just a special sentinel value that other iterators will compare equal to after you’ve iterated across an entire container.That’s not really guaranteed though. Specifically, your insertions could cause rehashing, [Edit: here I’m more or less assuming that your two insertions are intended as a place-holder for some arbitrary number of insertions. You can figure out whether re-hashing happens for a specific load factor, number of insertions, etc., but you generally don’t want to — depending on it leads to fragile code] and rehashing invalidates iterators (§23.2.5/8). Although (as mentioned above) the iterator returned by
end()is often “special”, the standard doesn’t require that, so after the insertions, what you previously got fromendmay be invalid, so virtually nothing is required about it (including comparing equal to anything in particular).