2016-03-10 48 views
-1

我有一個std ::地圖是這樣的:std :: map值是空的,即使我分配了一個值?

std::map<std::string, std::string> imagePaths; 

在我的代碼後來我給它一個值,就像這樣:

imagePaths.insert(std::make_pair("Square.bmp", "Square")); 

然而,當我環槽地圖,顯示兩個這樣的第一和第二值:

for (auto iterator = imagePaths.begin(); iterator != imagePaths.end(); iterator++) 
{ 
    std::cout << "Loaded > " << imagePaths[iterator->first] << " image path : " << imagePaths[iterator->second] << std::endl; 
} 

我得到的輸出:

加載>方形圖像路徑:

而其餘的是,由於某種原因,空的,即使我給它的"Square.bmp"值。


無法弄清楚我做錯了什麼。 :/

回答

3

您正在使用錯誤的方式顯示地圖內容。

試試這個:

for (auto iterator = imagePaths.begin(); iterator != imagePaths.end(); iterator++) 
{ 
    std::cout << "Loaded > " << iterator->first << " image path : " << iterator->second << std::endl; 
} 

要使用的鍵使用.find()方法查找的值。在你的情況下,如果你執行這條語句:

std::map<std::string, std::string>::const_iterator i = imagePaths.find("Square.bmp"); 

std::string value = it->second; 

value將是「Square」。

+0

這是可行的,但如果我想打印出「Square」的值呢?我試過這個:'std :: cout << imagePaths [「Square」] << std :: endl;'這不起作用。 – BiiX

+0

很酷。你可能想把它標記爲答案:) –

+0

我會在2分鐘內,必須等待一會才接受。 :P – BiiX

1

std::map將該對中的第一個元素映射到第二個元素,但它不會以相反的方式工作。

除此之外,根本無法在循環中應用映射,因爲您已經可以通過迭代器訪問這兩個值。

相關問題