gpt4 book ai didi

c++ - 关于映射和迭代器的理论说明

转载 作者:太空狗 更新时间:2023-10-29 20:23:37 27 4
gpt4 key购买 nike

如果我有一个带有 map 的类作为私有(private)成员,例如

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

在我的 main 函数中,这两段代码会有区别吗?

代码1:

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

代码2:

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 中,我刚刚创建了一个新的 map 变量来保存从 getPlatforms() 函数返回的 map 。

无论如何,在我的真实代码中(我无法发布真实代码,但它直接对应于这个概念)第一种方式 (Code1) 导致运行时错误,无法访问某个位置的内存。

第二种方式可行!

您能告诉我这两段不同代码之间发生的事情的理论基础吗?

最佳答案

getPlatforms() 按值而不是引用返回 map ,这通常是个坏主意。

你已经展示了为什么这是一个坏主意的例子:

getPlatforms().begin() 是 map 上的迭代器,在使用迭代器之前就消失了,getPlatforms().end() 是 map 上的迭代器来自同一原始 map 的不同拷贝。

关于c++ - 关于映射和迭代器的理论说明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32202959/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com