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
  • 555,201
  • 31
  • 458
  • 770
  • 1
    Possible duplicate of [What are the basic rules and idioms for operator overloading?](https://stackoverflow.com/questions/4421706/what-are-the-basic-rules-and-idioms-for-operator-overloading) – user0042 Oct 06 '17 at 17:24
  • Btw keeping multipliers in vector would be significantly more efficient by memory and performance. In theory it could use more memory though, but that is very unlikely. – Slava Oct 06 '17 at 17:35
  • 2
    I recommend restructuring your program. Create a `Term` class, which has coefficient and exponent. A `Polynomial` would be a container of `Term`. – Thomas Matthews Oct 06 '17 at 17:42
  • @ThomasMatthews what kind of container? Perhaps a map? – n. m. could be an AI Oct 06 '17 at 20:59
  • Have you tried something? – n. m. could be an AI Oct 06 '17 at 21:01
  • 1
    Any kind of container, usually the "one dimensional", such as `std::vector`, `std::list`, `std::array` or a custom container. One cannot guarantee the order of the terms when using a `std::map`. – Thomas Matthews Oct 06 '17 at 21:02

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
  • 555,201
  • 31
  • 458
  • 770