vmatrizx
vmatrizx

Reputation: 11

error: no match for 'operator=' (operand types are 'std::map<int, double>::iterator

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

In the process of using iterator, it throws an error. If I replace it with
map<int, double>tem=other.monomial; and then operate on tem, then it run well. I know putting data in public is a bad habit, but now I just want to know why it throw this error. I am searching for a long time on net. But no use. Please help or try to give some ideas how to achieve this. Thanks in advance.

Upvotes: 1

Views: 3188

Answers (1)

Slava
Slava

Reputation: 44268

Problem is other is a const reference which making other.monomial const as well so only version of std::map::begin() that returns const iterator is available, but you try to assign it to regular iterator. Fix could be of changing your iterator type:

  map<int, double>::const_iterator iter;

but you better use auto instead or even better for range loop:

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

However it is not clear why you need to implement copy ctor manually at all, compiler generated will do what you need without any effort.

Upvotes: 4

Related Questions