0

I have Poly class that contains a polynomial in a map. How can I overload the += operator for it so that it adds together multipliers with the same exponential?

example:

4x²+2x+7 is contained as (2, 4), (1, 2), (0, 7)

class Poly {
    typedef std::map<int, int> Values;
    Values m_values;
public:
    typedef Values::const_reverse_iterator const_iterator;
    typedef Values::reverse_iterator iterator;
    int operator[](int exp) const;
    Poly& operator+=(Poly const& b);
    Poly& operator-=(Poly const& b);
};

Poly& Poly::operator+=(Poly const& b) {
    // ???
}
Remy Lebeau
  • 505,946
  • 29
  • 409
  • 696

1 Answers1

0

Try something like this:

Poly& Poly::operator+=(Poly const& b) {
    for (Values::const_iterator iter = b.m_values.begin(), end = b.m_values.end(); iter != end; ++iter) {
        Values::iterator found = m_values.find(iter->first);
        if (found != m_values.end()) {
            found->second += iter->second;
        }
    }

    return *this;
}

Poly& Poly::operator-=(Poly const& b) {
    for (Values::const_iterator iter = b.m_values.begin(), end = b.m_values.end(); iter != end; ++iter) {
        Values::iterator found = m_values.find(iter->first);
        if (found != m_values.end()) {
            found->second -= iter->second;
        }
    }

    return *this;
}
Remy Lebeau
  • 505,946
  • 29
  • 409
  • 696