I have a class Poly
which is a class for polynomials basically. Poly
has a private member of type std::map<int, int>
called values_
. I managed to overload the shift left operator <<
to be able to print my polynomial. for example if values_ have {(2,4), (1,0), (-1,-1)}
, where the first
is the exponent and second
is the multiplier, the printed string to the ostream shall be 4x2+0x1-1x-1
.
Now I am trying to find a way to overload the insertion operator >>
so that if the user inputs 4x2+0x1-1x-1
the polynomial should be stored as {(2,4), (1,0), (-1,-1)}
What are the steps to handle std::istringstream to translate the input to be a polynomial?
class Poly {
public:
typedef std::map<int, int> Values;
typedef Values::const_reverse_iterator const_iterator;
typedef Values::reverse_iterator iterator;
const_iterator begin() const { return values_.rbegin(); }
const_iterator end() const { return values_.rend(); }
iterator begin() { return values_.rbegin(); }
iterator end() { return values_.rend(); }
}
int operator[](int exp) const;
int& operator[](int exp) { return values_[exp]; }
private:
Values values_;
};
std::istream& operator>>(std::istream& is, Poly& p);
std::ostream& operator<<(std::ostream& os, const Poly& p);
int Poly::operator[](int exp) const {
Values::const_iterator it = values_.find(exp);
return it == values_.end() ? 0 : it->second;
}