2017-10-06 12 views
0

マップに多項式を含むPolyクラスがあります。 +=演算子をオーバーロードして、同じ指数関数を乗算器に加算する方法はありますか?C++マップを使用してクラスの+ =演算子をオーバーロードする方法?

例:

4x²+2x+7(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) { 
    // ??? 
} 
+1

の可能な複製を、[演算子のオーバーロードのための基本的なルールやイディオムは何ですか?]( https://stackoverflow.com/questions/4421706/what-are-the-basic-rules-and-idioms-for-operator-overloading) – user0042

+0

ベクトで乗数を保持するBtw rはメモリとパフォーマンスによって大幅に効率的になります。理論的には、より多くのメモリを使用することもできますが、それはほとんどあり得ません。 – Slava

+2

あなたのプログラムを再構築することをお勧めします。係数と指数を持つ 'Term'クラスを作成します。 '多項式'は 'Term'のコンテナです。 –

答えて

0

として含まれている。このような何か試してみてください:

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; 
} 
関連する問題