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

标签 c++ dictionary iterator

如果我有一个带有 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/

相关文章:

c++ - 避免模​​板参数中迭代器类型的累积

iterator - .cloned() 应该在 .filter() 之前还是之后

c++ - 映射类导致内存泄漏

c++ - 提取 try-catch 时出现运行时错误

c++ - Code::Blocks Debug模式:如果构建并运行我的代码会崩溃,但如果调试/继续则不会

python - 如何将字典格式的txt文件转换为python中的数据帧?

java - map 按值集合的大小排序

c++ - 在没有方法c++的类中插入数据

c++ - EXC_BAD_ACCESS(code=1, address=0x0) 在将 std::map 作为参数传递给虚函数调用时发生

c++ - 比较来自一个 vector 的迭代器时,什么会引发 'iterators are incompatible'?