问题描述
如果我有一个地图作为私人会员的课程,例如
If I have a class with a map as a private member such as
class MyClass
{
public:
MyClass();
std::map<std::string, std::string> getPlatforms() const;
private:
std::map<std::string, std::string> platforms_;
};
MyClass::MyClass()
:
{
platforms_["key1"] = "value1";
// ...
platforms_["keyN"] = "valueN";
}
std::map<std::string, std::string> getPlatforms() const
{
return platforms_;
}
在我的主要功能中,这两个代码之间有区别?
And in my main function would there be a difference between these two pieces of code?
Code1:
MyClass myclass();
std::map<std::string, std::string>::iterator definition;
for (definition = myclass.getPlatforms().begin();
definition != myclass.getPlatforms().end();
++definition){
std::cout << (*definition).first << std::endl;
}
Code2:
MyClass myclass();
std::map<std::string, std::string> platforms = myclass.getPlatforms();
std::map<std::string, std::string>::iterator definition;
for (definition = platforms.begin();
definition != platforms.end();
++definition){
std::cout << (*definition).first << std::endl;
}
在Code2中,我刚刚创建了一个新的地图变量来保存从getPlatforms()函数。
In Code2 I just created a new map variable to hold the map returned from the getPlatforms() function.
无论如何,在我的真实代码(我不能发布真正的代码,但它直接对应于这个概念)第一种方式(Code1)导致运行时错误,无法访问某个位置的内存。
Anyway, in my real code (which I cannot post the real code from but it is directly corresponding to this concept) the first way (Code1) results in a runtime error with being unable to access memory at a location.
第二种方式工作!
你能否启发我对这两种代码之间发生的事情的理论基础?
Can you enlighten me as to the theoretical underpinnings of what is going on between those two different pieces of code?
推荐答案
getPlatforms()
通过值返回地图,而不是引用,这通常是一个坏主意。
getPlatforms()
returns the map by value, rather than reference, which is generally a bad idea.
您已经显示了一个示例为什么这是一个坏主意:
You have shown one example of why it is a bad idea:
getPlatforms()。begin()
是地图上的迭代器在迭代器被使用之前, getPlatforms()。end()
是与同一个原始ma的不同副本的迭代器p。
getPlatforms().begin()
is an iterator on a map that is gone before the iterator is used and getPlatforms().end()
is an iterator on a different copy from the same original map.
这篇关于关于地图和迭代器的理论说明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!