简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM