I am trying to return a copy of an unordered_map from inside an unordered_map.

The following code illustrates my problem more clearly:

typedef std::unordered_map<std::string, int> Foo;
typedef std::unordered_map<std::string, Foo> FooContainer;    

...

FooContainer bar;
// etc

...

Foo GetSubmap(std::string name)
{
    // ???
}

I am not sure how I would go about doing this, as unordered_map.find(foo) returns an iterator for the container.

Many thanks in advance!

有帮助吗?

解决方案

If you want to return empty map if no element found you can do as simply as this:

Foo GetSubmap(std::string name)
{
    FooContainer::const_iterator f = bar.find( name );
    return f != bar.end() ? f->second : Foo();
}

Or you may throw exception in case no element found. You can also use bar[name], but you should know that it has side effect - empty Foo will be inserted into bar each time you lookup for non existing element.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top