<p>For an <code>std::map&lt;std::string, std::string&gt; variables</code>, I'd like to do this:</p>

<pre><code>BOOST_CHECK_EQUAL(variables["a"], "b");
</code></pre>

<p>The only problem is, in this context <code>variables</code> is <code>const</code>, so <code>operator[]</code> won't work :(</p>

<p>Now, there are several workarounds to this; casting away the <code>const</code>, using <code>variables.count("a") ? variables.find("a")-&gt;second : std::string()</code> or even making a function wrapping that. None of these seem to me to be as nice as <code>operator[]</code>. What should I do? Is there a standard way of doing this (beautifully)?</p>

<p><strong>Edit:</strong> Just to state the answer that none of you want to give: No, there is no convenient, beautiful, standard way of doing this in C++. I will have to implement a support function.</p>

```
find
```
is the idiomatic form. Casting away
```
const
```
is almost always a bad idea. You'd have to guarantee that no write operation is performed. While this can be reasonably expected of a read access on a map, the specification doesn't say anything about this.
If you
know
that the value exists you can of course forego the test using
```
count
```
(which is quite inefficient, anyway, since it means traversing the map twice. Even if you don't know whether the element exists I wouldn't use this. Use the following instead:
```
```
T const& item(map<TKey, T> const& m, TKey const& key, T const& def = T()) {
    map<TKey, T>::const_iterator i = m.find(key);
    return i == m.end() ? def : i->second;
}
```
```
/EDIT: As Chris has correctly pointed out, default-construction of objects of type
```
T
```
might
be expensive, especially since this is done even if this object isn't actually needed (because the entry exists). If this is the case, don't use the default value for the
```
def
```
argument in the above case.