Returning an empty vector of strings if key is not found

前端 未结 4 806
花落未央
花落未央 2021-01-13 09:34

I know it is a very bad idea, so other suggestions on how to do it efficiently will be well-received.

Here\'s the thing. I have map

4条回答
  •  天涯浪人
    2021-01-13 10:10

    How about this:

    std::vector find_by_key_maybe(const std::string & key)
    {
      std::map>::const_iterator it = themap.find(key);
      return it == themap.end() ? std::vector() : it->second;
    }
    

    Or even, if themap is non-const, and you also wish to add an empty vector into the map:

    std::vector find_by_key_and_insert_if_missing(const std::string & key)
    {
      return themap[key];
    }
    

    It's perfectly OK to return a vector by value, if that's what the situation calls for.

提交回复
热议问题