开发者

"Invalid initialization" error when reading from a map

I'm getting the following error when trying to build:

error: invalid initialization of non-const reference of type "std::vector<......"

Code:

class Config {
    public:
        std::vector<string>& GetValuesForList(std::string listName);

    private:
        std::map<std::string, std::vector<string> > lists;
    };

    inline std::vector<string>&
    Config::GetValuesForList(std::string listName) {
        return lists.find(listName);
    }

I've read up on it and seems to be because of C++ temporaries, but am unsure 开发者_StackOverflow社区how to resolve it. Any help would be greatly appreciated.

Thanks.


map::find returns iterator. So you should use it's second value:

    inline std::vector<string>&
    Config::GetValuesForList(std::string listName) {
        return lists.find(listName)->second;
    }


Do you want return lists.find(listName)->second;?

[Side note: lists is not a very good name for a thing that is a map of vector!]


std::map<T>::find() returns a std::map<T>::iterator, not reference to the value type. What you want is the below

  inline std::vector<string>&
    Config::GetValuesForList(std::string listName) {
         std::map<std::string, std::vector<string> >::iterator  itr = lists.find(listName);
         if (itr != lists.end()) {
             return itr->second;;
         } else {
           // What to do if not found.
         }
    }

As a note, if you want it to create a new empty vector if not found, then you can simplify the whole thing to

  inline std::vector<string>&
    Config::GetValuesForList(std::string listName) {
         return lists[listName]; // Creates a new vector if listname not found
    }


map::find() returns an iterator to pair<key,value>.

I think its better to write this:

std::vector<string>& Config::GetValuesForList(std::string listName) 
{
    return lists[listName];
}

If the key listName exists in the map, then it will return the associated value. Otherwise, it will create a new entry in the map, and will return the newly created std::vector<T> which would be empty.

I would also like to suggest you to add another function as bool DoesExist(std::string listName) which you may use to inspect, before calling the above function so as to avoid creating new entry if the key is not found:

bool DoesExist(std::string listName)
{
   return lists.find(listName) != lists.end();
}

Also, it would be better if you change the name lists to vecMap .

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜