c++ - 错误: 'operator=' 不匹配(操作数类型为 'std::map<int, double>::iterator

标签 c++ class iterator copy-constructor

     //a class used to make operations on Polynominal   
    class Polynominal
        {
        public:
            map<int, double> monomial;//int is exp,double is coefficient
            Polynominal();
            ~Polynominal();
            Polynominal(const Polynominal& other);
            /*...many functions*/
        };

        //copy constructor
        Polynominal::Polynominal(const Polynominal& other)
        {
            map<int, double>::iterator iter;

        /*Throw error here. If I replace it with 
           "map<int, double>tem=other.monomial;" 
           and then operate on tem, then it run well.*/
          for(iter=other.monomial.begin();iter!=other.monomial.end();iter++)
              monomial.insert(pair<int, double>(iter->first, iter->second));
        }

在使用iterator的过程中,抛出错误。如果我将它替换为
map<int, double>tem=other.monomial;然后对tem进行操作,然后运行良好。 我知道将数据公开是一个坏习惯,但现在我只想知道为什么会抛出这个错误。我在网上找了很久。但是没有用。请帮助或尝试提供一些想法如何实现这一目标。 提前致谢。

最佳答案

问题是 other 是一个 const 引用,它使 other.monomial 也成为常量,所以只有 std::map::begin() 的版本返回 const 迭代器可用,但您尝试将其分配给常规迭代器。修复可能是更改迭代器类型:

  map<int, double>::const_iterator iter;

但是你最好使用 auto 代替,或者更好地用于范围循环:

 for( const auto &p : other.monomial )
          monomial.insert( p );

但是不清楚为什么您需要手动实现复制构造函数,生成的编译器将毫不费力地完成您需要的工作。

关于c++ - 错误: 'operator=' 不匹配(操作数类型为 'std::map<int, double>::iterator,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49708155/

相关文章:

c++ - 如何使用节点在 C++ 中编写二叉搜索树的迭代器

c++ - std::multimap 获取两个范围

c++ - 在容器中存储模板化对象

c++ - 在 C++ 中, 'Node' 是一个类, 'node' 是 'Node' 的实例。为什么 "*node = nullptr "是错误的,而 "*node = NULL"是正确的?

c++ - friend 模板定义。何时何地包含 <T>?

python - 是否可以选择将哪些 kwargs 传递给 python 中的父类(super class)?

C++ vector 迭代器错误

c++ - 如何从 MNIST 数字数据库中读取像素并创建 iplimage

java - 从类的完全限定名中获取类

Java 性能/内存消耗 : Class vs. 数组