[英]std::map value is empty even though i assigned a value?
I have a std::map like this : 我有一个像这样的std :: map:
std::map<std::string, std::string> imagePaths;
Later in my code I give it one value, like this : 稍后在我的代码中,我给它一个值,如下所示:
imagePaths.insert(std::make_pair("Square.bmp", "Square"));
However, when I loop trough the map and display both first and second values like this : 但是,当我循环通过地图并显示第一个和第二个值时,如下所示:
for (auto iterator = imagePaths.begin(); iterator != imagePaths.end(); iterator++)
{
std::cout << "Loaded > " << imagePaths[iterator->first] << " image path : " << imagePaths[iterator->second] << std::endl;
}
I get the output : 我得到的输出:
Loaded > Square image path :
已加载>方形图像路径:
And the rest is, for some reason empty, even though I gave it a value of "Square.bmp"
. 剩下的,由于某种原因,都是空的,即使我给它取了一个
"Square.bmp"
值。
Can't figure out what I'm doing wrong. 无法弄清楚我在做什么错。 :/
:/
You are using the wrong way to display a map content. 您使用了错误的方式来显示地图内容。
Try this: 尝试这个:
for (auto iterator = imagePaths.begin(); iterator != imagePaths.end(); iterator++)
{
std::cout << "Loaded > " << iterator->first << " image path : " << iterator->second << std::endl;
}
To lookup a value using the key you use .find()
method. 要使用键查找值,请使用
.find()
方法。 In your case, if you execute this statement: 就您而言,如果执行此语句:
std::map<std::string, std::string>::const_iterator i = imagePaths.find("Square.bmp");
std::string value = it->second;
value will be "Square". 值将为“平方”。
The std::map
maps the first element of the pair to the second, it does not work the other way round. std::map
将对中的第一个元素映射到第二个,反之则不起作用。
Aside from that, it does not make sense to apply the mapping in your loop at all because you already can access both values via the iterator. 除此之外,根本没有必要在循环中应用映射,因为您已经可以通过迭代器访问这两个值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.