>So to answer that question, no, it isn't a member of polynomial. So i guess i should have

>the '<' operator in my term struct?

Yes. At the moment you're overloading a comparison for `Polynomial < term`

. Since you want a `term < term`

type of comparison, you should overload '<' for `term`

.

## John A 1,896

## orangejuice2005

Ah thnx, that made sense and those errors are gone now. I just have 1 more errors left: `1\poly.cpp(24) : error C2676: binary '[' : 'const Polynomial' does not define this operator or a conversion to a type acceptable to the predefined operator`

This is what the error points too: lines 24 and 25

```
Polynomial operator+( const Polynomial& p1, const Polynomial& p2 )
{
Polynomial result;
term r;
vector<term>::const_iterator it;
it = p1.poly.begin();
vector<term>::const_iterator it2;
it2 = p2.poly.begin();
do
{
for(int i = 0; i<p1.poly.size(); i++)
{
for (int j=0; j<p2.poly.size(); j++)
{
if(it->expo == it2->expo && it->var == it2->var)
{
r.co = it->co + it2->co;
r.var = it->var;
r.expo = it->expo;
result.poly.push_back(r);
}
else
{
result.poly.push_back(p1[i]);
result.poly.push_back(p2[j]);
}
}
it++;
it2++;
}
}while (it !=p1.poly.end() || it2 !=p2.poly.end());
return result;
}
```

Am just trying to have the code add 2 terms with like exponents and copythe rest of the terms into a vector called result.

## John A 1,896

For lines 24 and 25, shouldn't it be like this?

```
result.poly.push_back(p1.poly[i]);
result.poly.push_back(p2.poly[j]);
```

## orangejuice2005

Thnx for spotting that! Sorry am still trying to get to all this. So my program compiles and runs but doesn't completely do what i wanted it to do right.

For 1 - Everytime i enter a polynomial and i want it displayed......it doesn't display the "^" symbol and ignores the term's exponents. It also ignores coefficients with no variables or exponents

I enter `4x^2+3x+4`

I get `4x 3x`

And when i ask it to display the number of terms in the vector, instead of 3, it prints 2

Something is wrong with the way i overload my input and output operator.

## John A 1,896

Post your updated code.

## orangejuice2005

I'll attach the necessary files so you can see what its doing.

```
#include "POLY.h"
#include <iostream>
using namespace std;
istream& operator>> (istream& stream, Polynomial& pnomial)
{
term t;
bool symbol = true;
pnomial.poly.erase (pnomial.poly.begin(), pnomial.poly.end());
while (stream) // (while not EOF)
{
if (stream.peek() == ';') // are we at the end of the poly?
{ // yes
stream.get(); // read the ';'
break; // end the loop
}
else
{
if (stream.peek() == '+') stream.get(); // skip any '+'s
stream >> t.co; // read the coefficient
if (stream.peek() =='x')
stream >> t.var; // read the 'x'
if (stream.peek() =='^')
{
symbol = true;
stream.get(); // read the '^'
}
if (symbol = true)
{
stream >> t.expo; //read the exponent if there is a '^' before it;
}
pnomial.poly.push_back(t);
}
}
return stream;
}
ostream& operator<< (ostream& stream, Polynomial& pnomial)
{
term t;
for (int i = 0; i < pnomial.poly.size(); i++)
{
if (pnomial.poly[i].expo == 0)
stream << pnomial.poly[i].co << "\t"; // print coefficient only if exponent is 0
if (pnomial.poly[i].expo == 1)
stream << pnomial.poly[i].co+"+"<<pnomial.poly[i].var<< "\t"; // print coefficient plus variable if exponent = 1
else
stream << pnomial.poly[i].co+"+"<<pnomial.poly[i].var+"^"<<pnomial.poly[i].expo<< "\t"; // print format 7x^3
}
return stream;
}
Polynomial::Polynomial()
{
reset(); //default
}
void Polynomial::reset()
{
poly.clear(); //clear polynomial
}
int Polynomial::number_of_terms()
{
return poly.size(); //return number of elements in vector or number of terms in polynomial
}
Polynomial operator+( const Polynomial& p1, const Polynomial& p2 )
{
Polynomial result;
term r;
vector<term>::const_iterator it;
it = p1.poly.begin();
vector<term>::const_iterator it2;
it2 = p2.poly.begin();
do
{
for(int i = 0; i<p1.poly.size(); i++)
{
for (int j=0; j<p2.poly.size(); j++)
{
if(it->expo == it2->expo && it->var == it2->var)
{
r.co = it->co + it2->co;
r.var = it->var;
r.expo = it->expo;
result.poly.push_back(r);
}
else
{
result.poly.push_back(p1.poly[i]);
result.poly.push_back(p2.poly[j]);
}
}
it++;
it2++;
}
}while (it !=p1.poly.end() || it2 !=p2.poly.end());
return result;
}
void Polynomial::sort()
{
poly.begin(), poly.end();
}
bool term::operator< (const term& other_term) const
{
return expo < other_term.expo;
}
```

```
#ifndef POLY_H
#define POLY_H
#include <iostream>
#include <vector>
using namespace std;
struct term
{
int co;
int expo;
char var;
bool operator< (const term& other_term) const;
};
class Polynomial
{
friend istream& operator>> (istream& stream, Polynomial& pnomial);
friend ostream& operator<< (ostream& stream, Polynomial& pnomial);
public:
// The list of terms in the polynomial
// (not necessarily ordered)
vector<term> poly;
// default constructor
Polynomial();
// empties the polynomial of all terms
void reset();
// sort the terms from the highest to lowest exponent
void sort();
// add two polynomials
friend Polynomial operator+( const Polynomial& p1, const Polynomial& p2);
// returns the number of terms in the polynomial
int number_of_terms();
};
#endif
```

```
#include <iostream>
#include <vector>
#include "POLY.h"
using namespace std;
void menu (void)
{ cout<<endl;
cout<<"1. Enter a polynomial"<<endl;
cout<<"2. Reset the polynomial"<<endl;
cout<<"3. Add"<<endl;
cout<<"4. Number of Terms" << endl;
cout<<"5. Print Polynomial"<<endl;
cout<<"6. Quit"<<endl;
cout<<"Enter selection>";
}
void add(Polynomial& P)
{
Polynomial p2, result;
p2.reset();
result.reset();
//enter values for second polynomial
cout<<"Enter terms for second polynomial. Enter ; to stop."<<endl;
cin>>p2;
result = P + p2;
cout<<"Result for added polynomial is:"<<endl;
cout<<"First Polynomial + Second Polynomial: "<<result<<endl;
cout<<"Number of Terms: "<<result.number_of_terms()<<endl;
}
int main (void)
{
int choice;
//declare a Polynomial
Polynomial p;
p.reset();
do {
//print menu
menu();
cin>>choice;
switch (choice) {
case 1 :cout<<endl<<"Enter polynomial(Input must be of the form: 4x^2+3x+6).Enter ; to stop."<<endl;
cin>>p;
cout<<endl;
break;
case 2 : p.reset();
cout<<endl<<"Polynomial reset"<<endl;
break;
case 3: add(p);
break;
case 4: cout<<endl<<"Number of Terms is "<<p.number_of_terms()<<endl;
break;
case 5: cout<< "The polynomial is: " << p << endl;
break;
case 6: cout<<endl<<"Thanks and goodbye."<<endl;
break;
default : cout<<endl<<"Invalid command. Try again."<<endl;
}
} while (choice != 6);
}
```

## John A 1,896

At the moment I don't have access to a debugger, nor do I feel like adding lots of couts to see where your program goes wrong. Glancing over your code, there's nothing obviously wrong, so I'll recommend two different options for you: use a debugger. Your IDE/compiler will usually come with one. If you don't know how to use it, learn. I'd start by watching all the variables very carefully when you run your overloaded '>>' function for `Polynomial`

. Once you've ensured that that's loading correctly, move on to the next function.

If you don't for some reason have a debugger available to you, do the next best thing: scatter couts liberally throughout functions that you suspect are problematic. The idea is that you can see what your variables are doing after various function calls. It's a crude method of debugging, but it works.

## Duoas 1,025

Actually, your program has a few I/O errors that I'm sorry to say I didn't catch earlier. I'll list them all here for you though.

**Polymain.cpp: line 15**

Just as a personal stylistic preference, I'd add a single space after the prompt, as: `cout<<"Enter selection> ";`

This isn't a bug, though. Just style. :)

**1. Polymain.cpp: lines 44, 47**

User input should generally be done on a line-by-line basis (that is, input an entire line as a string, then parse the string) but C++ lends itself to professors having you learn UI with the >> and << operators of the cin and cout streams. These operators do what they are supposed to do, but a one-sided education in their use produces some *very bad* and buggy I/O programs.

On the line indicated, you have the user input an integer. That's fine (unless the user inputs, say 'a'). I'll defer lecturing to the optional part at the end of my post and just fix egregious errors here.

After inputting the integer there remains a newline sitting in the input stream. The user *had* to press ENTER to send the number to the program, so we really do need to remove the newline before continuing. (That way the newline doesn't contaminate more input --which it does in your program, btw.) Best to avoid the possibility of error either way. Change line 44 to read:

```
cin>>choice;
cin.ignore( numeric_limits<streamsize>::max(), '\n' );
```

The same problem occurs on what is now line 48. You input a polynomial, but the user *had* to press ENTER at least once. The ';' is brilliant, but that only separates polynomials from other *non-whitespace* items in the input stream. So, change line 48 to read:

```
cin>>p;
cin.ignore( numeric_limits<streamsize>::max(), '\n' );
```

**Poly.cpp: operator>>**

Your logic leaves some holes in it. (Don't feel bad, it takes a good amount of time to be able to think yourself through *every* possibility. Again, I'll focus only on parsing *correct* input.)

The clear() method is nicer than erase( begin, end ). (Not a bug, but just a suggestion.)

```
istream& operator>> (istream& stream, Polynomial& pnomial)
{
term t;
pnomial.poly.clear();
```

The first problem is that stream.peek() returns the *very next* character in the input stream, which may be a whitespace character. We are interested in ignoring whitespace, so we'll have to prefix the call(s) to peek() with something that gets rid of any leading whitespace.

```
while (stream)
{
stream >> ws; // We don' wan' no steeenkin' whitespace
if (stream.peek() == ';')
{
// We've found the end of our polynomial.
// Time to stop reading the input stream.
// Read the terminating ';' and quit the loop.
stream.get();
break;
}
```

Now we know that the next call(s) to peek() (without any interleaving input) will not return a whitespace character.

Since you are **break**ing from the loop if you read a ';', there is no need to put an **else** after the **if**.

Remember, if you read in some value (int, char, etc.) and want to use peek() again, you must first `stream >> ws;`

```
if (stream.peek() == '+') stream.get();
stream >> ws;
// We'll do some more peek()ing in a moment.
```

You might want to take a moment and consider why I didn't bother to put a >>ws before the peek() also.

OK, on to big logic errors.

This one is a freebie. What if one of the terms is something like `-x`

? If there isn't a coefficient you must assume 1, and set **t.co** to 1 or -1 as appropriate. In any case, t.co *must* be given a value. So, Let's change the last code fragment to:

```
switch (stream.peek())
{
case '+': t.co = 1; stream.get(); break;
case '-': t.co = -1; stream.get(); break;
}
stream >> ws;
// We'll do some more peek()ing in a moment.
```

I could have use a couple of if else statements, but this is cleaner and easier to read. Now all you need is to read the coefficient, if it *is* there:

`if (stream.peek() != 'x') stream >> t.co;`

I noticed that you added a **t.var** char variable, which is nice, but so far we have assumed that the variable is named 'x'. You might want to take a look at the isalpha() function included with <cctype>. However, this opens up another can of worms. Right now perhaps you should just insist that the variable is named 'x' and forget the **t.var** member.

The next part has some further thoughts:

If the next (peek()ed) item is an 'x', then read the 'x'.

There will not be an exponent if there is no 'x'.

Don't forget to skip whitespaces between reading the 'x' and peek()ing for an '^'.

If there is no 'x', then the exponent is zero.

If there is an 'x', but no '^', then the exponent is one.

**Poly.cpp: operator<<**

Once you have fixed the input operator, you'll need to spend some more time on this to make it work right. I'm out of time now so I can't go into more detail.

You'll also have to wait on the promised lecture on user input methods. ;)

Hope this helps for now.

John A
commented:
Good work. I'm too lazy to do that much correction. :) +13

## orangejuice2005

much respect joeprogrammer and Duoas

Yeh at the moment both my i/o overload needs to be revamped

I made the necessary corrections duoas but while i was doing so, this is reagarding the input operator, i either had the program going in an infinite loop or it doesn't recognize constants.....it keeps thinking the 6 in 4x^2+3x+6 is an exponent of 3x

That messes with the number of terms actually in the vector and has my << operator print out an incorrect polynomial. Oh and how do i get rid of the extra + sign it prints out at the end of the polynomial printout

```
istream& operator>> (istream& stream, Polynomial& pnomial)
{
term t;
bool symbol = true;
pnomial.poly.clear();
while (stream)
{
stream >> ws; // skip over those whitespaces
if (stream.peek() == ';')
{
// We've found the end of our polynomial.
// Time to stop reading the input stream.
// Read the terminating ';' and quit the loop.
stream.get();
break;
}
if (stream.peek() == '+') stream.get(); // skip any '+'s
stream >> ws;
switch (stream.peek())
{
case '+': t.co = 1; stream.get(); break;
case '-': t.co = -1; stream.get(); break;
}
stream >> ws;
if (stream.peek() != 'x')
{
stream >> t.co; // read the coefficient
t.expo = 0; // set exponent to zero
}
else
{
stream.get(); // read the x if present
}
stream >> ws;
if (stream.peek() =='^')
{
symbol = true;
stream.get(); // read the '^'
}
if (symbol = true)
{
stream >> t.expo; //read the exponent if there is a '^' before it
}
else
{
t.expo = 1; exponent is set to 1 if '^' is not present
}
pnomial.poly.push_back(t);
}
return stream;
}
```

Output << op

```
ostream& operator<< (ostream& stream, Polynomial& pnomial)
{
term t;
for (int i = 0; i < pnomial.poly.size(); i++)
{
stream << pnomial.poly[i].co<<"x^"<<pnomial.poly[i].expo<<"+";
//if (pnomial.poly[i].expo == 0)
//stream <<"+"<<pnomial.poly[i].co << "\t"; // print coefficient only if exponent is 0
//if (pnomial.poly[i].expo == 1)
//stream << pnomial.poly[i].co<<"x"<<"+"<<"\t"; // print coefficient plus variable if exponent = 1
//else
//stream << pnomial.poly[i].co<<"x^"<<pnomial.poly[i].expo<<"+"<<"\t"; // print format 7x^3
}
return stream;
}
```

parsing, tokenizing, those sound scary. I'll be looking forward to u're lecture on inputs wheneva!

oh wow cool smiles.....lets see :D

## Duoas 1,025

That's because you didn't *replace* lines 17..18 with lines 20..25, as I indicated.

That should fix it. As a note, however, separating line 38 from 34 introduces the possibility to read incorrect input. Here's my take:

```
istream& operator>> (istream& stream, Polynomial& pnomial)
{
term t;
pnomial.poly.clear();
while (stream)
{
stream >> ws;
if (stream.peek() == ';')
{
stream.get();
break;
}
t.co = 1;
if (stream.peek() == '+') stream.get();
else if (stream.peek() == '-') {
t.co = -1;
stream.get();
}
stream >> ws;
if (stream.peek() != 'x') stream >> t.co;
if (stream.peek() == 'x')
{
stream >> t.var;
stream >> ws;
if (stream.peek() == '^')
{
stream.get();
stream >> t.expo;
}
else t.expo = 1;
}
else t.expo = 0;
pnomial.poly.push_back( t );
}
}
```

Notice how I get to line 30 only if there is an 'x' read. (That way, you can't have "12^3" as a term.)

Keep in mind that neither of our codes are perfect (and could use some significant work) but they do the job on *correct* input. Which is probably good enough for your professor.

Don't just copy my code into your project. Make sure you know what you are doing (I think you do have a pretty good idea, though).

The next trick is to fix your output to display a polynomial correctly. Just as you did with the input (which I feel justified having helped you so much, since input is *tricky*) you should start by making an output routine that just draws the basic polynomial: `4x^2+3x^1+6x^0;`

then add stuff to get rid of stuff you don't need.

Don't forget that ';' at the end...

Hope this helps.

## orangejuice2005

Yeh you practically had what you did explained in your previous post and now that you altered the code like you did, i understand now.

With that, my output operator works but only if its the polynomial in the vector is sorted and in canonical form.

I tried calling the sort function that's in my .cpp file but it doesn't work. It won't sort the terms and am pretty sure i have it right but it won't do it.

## orangejuice2005

Just wanted to say i fixed my sort method......man it takes me hours to figure out something without direction

Am almost done, its just my + operator thats acting up. It does what its supposed to do but it does it way too mnay times......adding 2 polynomials with 3 terms each produces a polynomial with 81 terms......

## orangejuice2005

Progress report!

So i managed to take it down to where it only duplicates the terms 3 times each for a total of 9 terms. Where i incremented the iterators largely affected this. I wanted to increment the iterators earlier but i get an error when i do that (saying something about `the vector iterators not dereferencable`

)

```
Polynomial operator+( const Polynomial& p1, const Polynomial& p2 )
{
Polynomial result;
term r;
vector<term>::const_iterator it;
it = p1.poly.begin();
vector<term>::const_iterator it2;
it2 = p2.poly.begin();
do{
for(int i = 0; i<p1.poly.size(); i++)
{
for (int j = 0; j<p2.poly.size(); j++)
{
if(it->expo == it2->expo)
{
r.co = it->co + it2->co;
r.expo = it->expo;
result.poly.push_back(r);
if ( it->expo != it2->expo)
{
result.poly.push_back(p1.poly[i]);
result.poly.push_back(p2.poly[j]);
}
}
}
it++;
it2++;
}
sort(result.poly.begin(), result.poly.end(), term());
}while(it != p1.poly.end() || it2 != p2.poly.end());
return result;
}
```

## JRM 107

I'm coming in late here, but I have a question.

If you are adding poly's with the same three terms,

how do you end up with 9 terms?

wouldn't you have the same three, but just more or less of each at the end of the addition?

## orangejuice2005

`P1 = 4x^2+3x+6`

+ `P2 = 4x^2+3x+4`

gets me `8x^2+8x^2+8x^2+6x+6x+6x+101010`

See? 3 instances of each...i don't know why it does that.

## JRM 107

`P1 = 4x^2+3x+6`

+`P2 = 4x^2+3x+4`

gets me`8x^2+8x^2+8x^2+6x+6x+6x+101010`

See? 3 instances of each...i don't know why it does that.

Yup, you've got some issues there.

the answer, of coarse, SHOULD BE:

8x^2+6x+10.

Your function probably doesn't now how to do math in that form. THAT's the trick!

Why don't you just strip off the x terms add the integers, then display with the terms?

## orangejuice2005

## iamthwee 1,547

Honey why are you using a nested for loop for poly addition?

## Lerner 582

You appeared to have too many loops and too many calls to push_back().

See if this works better.

```
Polynomial operator+(const Polynomial& p1, const Polynomial& p2)
{
Polynomial result;
term r;
vector<term>::const_iterator p1Current = p1.poly.begin();
vector<term>::const_iterator p1End = p1.poly.end();
vector<term>::const_iterator p2Current;
vector<term>::const_iterator p2End = p2.poly.end();
for( ; p1Current != p1End; ++p1Current)
{
for (p2Current = p2.poly.begin() ; p2Current != p2End;
++p2Current)
{
if(p1Current->expo == p2Current->expo &&
p1Current->var == p2Current->var)
{
r.co = p1Current->co + p2Current->co;
r.var = p1Current->var;
r.expo = p1Current->expo;
result.poly.push_back(r);
}
}
}
return result;
}
```

I think that will work if p1 and p2 have same degree and same number

of terms, which is the simplest scenario of adding two polynomials.

Note: I didn't review all of your code to be sure the above

function is consistent with the remainder of your code. The above

should be viewed as an example to generate ideas, not as a solution.

If you want to be able to add two polynomials that many not

have the same degree then work needs to done to the above function.

For example say you have the following system:

p1 = 5x;

p2 = 2x^3 + 4x^2 + 3;

result = 2x^3 + 4X^2 + 5x + 3;

Unfortunately, the above code will give result of zero if only the non-

zero terms are included Polynomial objects, and will give only 5x + 3

if terms with coefficients of zero are included in Polynomial objects.

Therefore, I would argue to include terms with zero coefficients in

Polynomial objects, eventhough they typically wouldn't be displayed

(there are other ways to deal with this issue, as you've already

discovered).

An additional concern given the above code, is that there is no way

to get the 2x^3 and 4x^2 terms from p2 into result.

But, if we could get the polynomial with the largest degree to always be

in the outer loop and the polynomial with the smallest degree to always

be in the inner loop, then the format will still work with only minor

adjustments. Here's how that might look.

```
Polynomial operator+(const Polynomial& p1, const Polynomial& p2)
{
if(p1.degree < p2.degree)
{
Polynomial largest(p2); //use copy constructor
Polynomial smallest(p1);
}
else
{
Polynomial largest(p1);
Polynomial smallest(p2);
}
Polynomial result;
term r;
vector<term>::const_iterator currentLarge = largest.poly.begin();
vector<term>::const_iterator endLarge = largest.poly.end();
vector<term>::const_iterator currentSmall;
vector<term>::const_iterator endSmall = smallest.poly.end();
for( ; currentLarge != endLarge; ++currentLarge)
{
for (currentSmall = smallest.poly.begin() ; currentSmall != endSmall;
++currentSmall)
{
if(currentLarge->expo == currentSmall->expo &&
currentLarge->var == currentSmall->var)
{
r.co = currentLarge->co + currentSmall->co;
r.var = currentLarge->var;
r.expo = currentLarge->expo;
result.poly.push_back(r);
}
else
result.poly.push_back(*currentLarge);
}
}
return result;
}
```

As another wrinkle, if the degree of p1 and p2 are the same then the degree

of result will be at most the same degree as p1 and p2, but may be smaller

if the coefficient of the highest order term(s) is(are) zero. For example,

in the system:

p1 = 2x;

p2 = -2x;

result = 0;

This means result.degree == 0, not 2 as for p1 and p2.

I'll leave it up to you how to adjust result.degree if the sum of

two polynomials yields coefficient(s) of zero in the high(est) order term(s).

orangejuice2005
commented:
Thanks a lot lerner for the help! +1

## orangejuice2005

## iamthwee 1,547

No, you need two for loops, but they should not be nested.

Think about it.

## Duoas 1,025

Coding is the process whereby you take a complicated task and break it down into simpler tasks. If you can't make it so simple you feel a two-year-old could have written it, then you are thinking too hard.

Personally, I would have my operator+ just concatenate the addend to the augend, then use the sort() method to arrange things in order and then join like powers...

## orangejuice2005

Lerner you were right, the extra push_back calls were the cause of my problem. Now these wrinkles that you mentioned showed up and i played around with the hint you gave me to try to solve my problem but i just kept running into dead ends.

iamthwee

- Thought about it and got

And with that, i decided to do it the way Duoas mentioned but how do i compare 2 elements within the same vector? in other words how do i combine the terms with like exponents?

```
Polynomial operator+(const Polynomial& p1, const Polynomial& p2)
{
Polynomial p3, result;
term r;
vector<term>::const_iterator p1Current = p1.poly.begin();
vector<term>::const_iterator p1End = p1.poly.end();
vector<term>::const_iterator p2Current;
vector<term>::const_iterator p2End = p2.poly.end();
for( ; p1Current != p1End; ++p1Current)
{
result.poly.push_back(*p1Current);
}
for (p2Current = p2.poly.begin() ; p2Current != p2End; ++p2Current)
{
result.poly.push_back(*p2Current);
}
sort(p3.poly.begin(), p3.poly.end(), term());
// combine terms with like exponents
if (p1Current->expo == p2Current->expo) // this is wrong i know i can't just do this
{
// compare with *iters and add terms
}
return result;
}
```

## JRM 107

Unless there is some code elsewhere, i see no way to differentiate one exponent from another. The boolian expression as written only evaluates at an ascii level. It knows nothing about powers of x. You are also advancing one character at a time, so the code is seeing a

sequence: 3,x,^,2 which need to be processed according to their respective significance. You have to capture the variables and their powers to know what gets added to what. I think you can use isalpha() and isadigit() to do that.

Progress report!

So i managed to take it down to where it only duplicates the terms 3 times each for a total of 9 terms. Where i incremented the iterators largely affected this. I wanted to increment the iterators earlier but i get an error when i do that (saying something about`the vector iterators not dereferencable`

)`Polynomial operator+( const Polynomial& p1, const Polynomial& p2 ) { Polynomial result; term r; vector<term>::const_iterator it; it = p1.poly.begin(); vector<term>::const_iterator it2; it2 = p2.poly.begin(); do{ for(int i = 0; i<p1.poly.size(); i++) { for (int j = 0; j<p2.poly.size(); j++) { if(it->expo == it2->expo) { r.co = it->co + it2->co; r.expo = it->expo; result.poly.push_back(r); if ( it->expo != it2->expo) { result.poly.push_back(p1.poly[i]); result.poly.push_back(p2.poly[j]); } } } it++; it2++; } sort(result.poly.begin(), result.poly.end(), term()); }while(it != p1.poly.end() || it2 != p2.poly.end()); return result; }`

## Duoas 1,025

**JRM**, please take the time to read the whole thread before jumping to conclusions. His polynomial is expressed as a vector of terms. Each term is composed of a coefficient and an exponent.

**orangejuice2005**

Why don't you use your sort() method? `p3.sort();`

Then, all the terms with the same exponent will be adjacent. For example, `4x^2 -3x -6 +9x^3 -2x^2 +7`

becomes `9x^3 +4x^2 -2x^2 -3x -6 +7`

Terms with like exponents: `9x^3 + (4x^2 -2x^2) -3x +(-6 +7)`

Combining them is just addition and subtraction of the coefficients: `9x^3 +2x^2 -3x +1`

1. After the sorting, just loop through the terms.

2. Inside that loop, check to see if the next term (if any) has the same exponent. If so,

combine (add) the terms. Loop until the next term has a different exponent or you reach the end.

3. Continue with the outer loop until all done.

Hope this helps.

## JRM 107

Sorry if I missed something. Ok, but how does he add mixed types? Each term is a mixed type in it's own right, unless x is set =1 , but the ^ isn't a valid math operator in C++ unless he overloaded a function to make it so.

I guess I'm a bit confused now...

JRM, please take the time to read the whole thread before jumping to conclusions. His polynomial is expressed as a vector of terms. Each term is composed of a coefficient and an exponent.

orangejuice2005

Why don't you use your sort() method?`p3.sort();`

Then, all the terms with the same exponent will be adjacent. For example,`4x^2 -3x -6 +9x^3 -2x^2 +7`

becomes`9x^3 +4x^2 -2x^2 -3x -6 +7`

Terms with like exponents:`9x^3 + (4x^2 -2x^2) -3x +(-6 +7)`

Combining them is just addition and subtraction of the coefficients:`9x^3 +2x^2 -3x +1`

1. After the sorting, just loop through the terms.

2. Inside that loop, check to see if the next term (if any) has the same exponent. If so,

combine (add) the terms. Loop until the next term has a different exponent or you reach the end.

3. Continue with the outer loop until all done.Hope this helps.

## Duoas 1,025

Yes, you are confused because you are mixing C++ and the OP's syntax for a polynomial. They are distinct things.

In textual representations, both `x^y`

and `x**y`

are common to mean "raise x to the power of y". This has absolutely nothing to do with C++.

A *term* is a multiplicative value. Hence, 4x is "4 times whatever 'x' is". You can add like terms (that is, terms with the same *power* of x) easily: `4x + 2x = 6x`

But *unlike* powers cannot be added: `x**2 + x = ???`

Three oranges and two oranges are five oranges, but three oranges and two apples are still three oranges and two apples no matter how you look at it.

Hope this helps.

## orangejuice2005

Ok Duoas am down to the part where i gota add like terms and i understand what i have to do but i don't know how to do it. How do i compare an element an iterator points to, to the next element within the vector . Heres my poor attempt at it. I would have went further but i don't know how to comparee 2 elements in a vector...

```
vector<term>::iterator p3Current = result.poly.begin();
for ( ; p3Current !=result.poly.end(); ++p3Current)
{
if(p3Current->expo == ++p3Current->expo)
{
result.poly[p3Current->co]+result.poly[++p3Current->co];
}
}
```

JRM, each element withing a polynomial vector consist of two fields: coefficient and an exponent, which equals one term from a polynomial. Thats why i made a struct called term with specified fields. Also am assuming the only variable is x so that eliminated the problem you spoke off. I also have a bool compare to compare 2 exponents from different terms. I overloaded my input operator so the symbol '^' is read and ignored but alerts me to the presence of an exponent or not. By comparing the exponents from terms i am able to add like terms and so forth

## Duoas 1,025

You can't use the ++ operator like that.

You *can*, however, use it like this:

```
...iterator i1, i2;
for (i1 = result.poly.begin(); i1 != result.poly.end(); i1++)
{
i2 = i1 +1; // the next term, if any
if (i2 == result.poly.end()) break; // if there isn't any next term, you are done anyway...
if (i1->expo == i2->expo)
{
i1->co += i2->co; // add the terms
result.poly.erase( i2 ); // erase the next term
}
}
```

I *think* that should work.

You could also just use integer indices, as in `result.poly[i].expo`

and the like.

Hope this helps.

## JRM 107

I am very familiar with texual math and how to add polly's.( you might want to check out one of MY earlier posts where I added them) My confusion is how this is something that a C++ can deal with. You can't be possibly trying to sell me the idea that :

result =3x^2 + 4x^2 is going to somehow magically yeild 7x^2 in result?

NO WAY. People can do that abstraction, but C++ can't. Not without some special function.

What say you?

Yes, you are confused because you are mixing C++ and the OP's syntax for a polynomial. They are distinct things.

In textual representations, both

`x^y`

and`x**y`

are common to mean "raise x to the power of y". This has absolutely nothing to do with C++.A

termis a multiplicative value. Hence, 4x is "4 times whatever 'x' is". You can add like terms (that is, terms with the samepowerof x) easily:`4x + 2x = 6x`

Butunlikepowers cannot be added:`x**2 + x = ???`

Three oranges and two oranges are five oranges, but three oranges and two apples are still three oranges and two apples no matter how you look at it.Hope this helps.