On 17-Jun-15 1:14 AM, Christopher Pisz wrote:
> [...] I think I want to use this alternative, so I can promise
> the caller I won't alter their map. No sense in using find here, as far
> as I can tell. I've never used the "at" member though.
>
> void Foo(const std::map<int, std::vector<std::string> > & theMap)
> {
> std::vector<std::string> & stuff = std::vector<std::string>();
> try
> {
> stuff = theMap.at(1);
> }
> catch(std::out_of_range &)
> {
> // Leave the vector empty
> }
>
> // Iterate over the elements and do things.
> }
Since you have declared `stuff` as a simple reference to non-`const`,
the initialization won't compile. A reference to non-`const` can only be
initialized with an lvalue expression, such as a reference to a
variable. However, it's not necessary to have `stuff` as a reference.
Also, note that using exceptions for normal case code (essentially to
provide a default) has a high cost, relative to non-exception based
code. Exceptions as used for failure handling can be very efficient,
because there they enable you to not do repeated checking in the normal
case code. But exceptions used for normal case code do the opposite:
they add checking that would otherwise not be there.
I would instead do something like this:
void foo( vector<string> const& stuff )
{
// Do things.
}
void foo( map<int, vector<string>> const& the_map )
{
vector<string> const empty_vector;
foo( the_map.count(1) > 0?
the_map.at(1) : empty_vector );
}
But before doing that I'd check if the caller could explicitly provide
the information that lack of a 1-key implies.
And if measurements showed that repeated lookup was too inefficient, I'd
use a `find` and keep the resulting iterator.
Cheers & hth.,
- Alf
--
Using Thunderbird as Usenet client, Eternal September as NNTP server.