2011-08-12 19 views
0

我越來越試圖建立在下列錯誤時:「無效初始化」錯誤從地圖讀取

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

代碼:

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); 
    } 

我已經讀了它,似乎是因爲C++的臨時性,但我不確定如何解決它。任何幫助將不勝感激。

謝謝。

回答

2

map::find返回迭代器。所以,你應該使用它的第二個值:

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

非常感謝,完美的工作。 – MeanwhileInHell

2

你想return lists.find(listName)->second;

[附註:lists是不是該是vector一個map的事情非常好名字!]

+0

非常感謝,那完美地工作。 – MeanwhileInHell

0

map::find()返回一個迭代器pair<key,value>

我認爲它能夠更好地寫:

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

如果存在於地圖上的關鍵listName,那麼它將返回相關的值。否則,它將在地圖中創建一個新條目,並返回新創建的std::vector<T>,該條目將爲空。

我也想建議你添加其他功能,如bool DoesExist(std::string listName)你可以用它來檢查,調用上面的函數之前,以避免產生新的條目,如果關鍵是沒有找到:

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

此外,如果您將名稱lists更改爲vecMap會更好。

+0

但是,如果找不到密鑰,這將創建元素。 –

+0

@Oli:是的。我在回答中添加了這些信息。 – Nawaz

0

std::map<T>::find()返回std::map<T>::iterator,沒有參考值類型。你想要的是下面的

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. 
     } 
    } 

作爲一個說明,如果你想創建一個新的空載體,如果沒有找到,那麼你就可以簡化整個事情

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