I have an assignment dealing with polynomials and adding two of them together. Am using vectors to approach this and i have one vector assigned for coefficients and the other exponents

Am very very new to c++ and am at a lost.
Here is my + operator

Polynomial operator+(Polynomial& p1, Polynomial& p2);
{
	Polynomial p3;
	double sum;

	vector<double>::const_iterator iter;
	iter = coef.begin();
	vector<int>::const_iterator iter2;
	iter2 = expo.begin();
	
	vector<double>::const_iterator iter3;
	iter3 = p2.coef.begin();
	vector<int>::const_iterator iter4;
	iter4 = p2.expo.begin();
	
    for (i = 0; i<coef.size(); i++)
		if (*iter2 = *iter4)
			sum = 

	return p3;
}

i don't know if what am doing is right or how to add 2 elements in a vector together after making sure the p1 and p2 exponents are equal. Please any help is appreciated

On lines 7 and 9 you forgot to say [b]p1.[/b]coef.begin() , etc.

Line 17 should have a == , not a = .

Your iterators have terrible names. Try
iter --> icoef1
iter2 --> iexpo1
iter3 --> icoef2
iter4 --> iexpo2
This will help.

Now, just remember, every time you increment an iterator to p1 you have to increment both.

if (I want to see the next term in p1) {
  icoef1++;
  iexpo1++;
  }

Likewise for p2's iterators.

Now you'll have to think about how to loop through the polynomials. Remember, you can only sum terms that have the same exponent. Are your polynomials stored in canonical form? (Meaning, that exponents start high and get smaller left to right, as: 4x^4 + 2x^2 - 7x ? How you find matching terms will be easier if it is.)

You will have to find matching exponents and add the coefficients, then push_back() the resulting coef/expo values in p3.

Hope this helps.

(Personally, I would forget the hard stuff and just make a routine that normalizes a polynomial. For example, given 4x^2 +3 and 2x^4 +2x^2 -7 , you could just concatenate the two into one: 4x^2 +3 +2x^4 +2x^2 -7 then normalize it into: 2x^4 +6x^2 -4 )

Can you so much Duoas for replying and i feel as if i've made this too complicated for myself and that i should you the full picture of what am doing.

These are the credentials:
- create a polynomial
- return the number of terms in a polynomial
- empty the polynomial (remove all items)
- add two polynomials together
- Read a polynomial from the input stream
- Print a polynomial to an output stream

Here is my class (Poly.h)

#ifndef poly
#define poly
#include <iostream>
#include <vector>

using namespace std;

struct term         // i decided to struct a term so that way i won't have to deal with 2 vectors
{
	int co;
	int expo;
};

class Polynomial
{
	friend istream& operator>> (istream& stream, Polynomial& poly);
	friend ostream& operator<< (ostream& stream, Polynomial& poly);

	public:
	
		Polynomial();                    //default constructor
		
                         // c for coefficient, e for exponent (format of input (c, e)?)
                        Polynomial( int c, int e);  
                       
		void initialize(int c, int e);
		
                        //empties vector
                        void reset();               
		
                         // sort constructor to have it sort the terms according to the exponent
                        void sort(); 
		
		vector<term> poly;   // a vector of terms
                       
                        // add operator
		Polynomial operator+(const Polynomial& p1, const Polynomial& p2); 
                       
                        //get number of terms in polynomial
		int get_term();
}
#endif

My implentation ( needs a lot of help am still trying to figure out how to make methods to achieve end means)

#include "Poly.h" 
#include <iostream> 

using namespace std;

Polynomial::Polynomial()
{
	reset();
	//default
}
void reset()
{
	term.erase (term.begin(), term.end());
}	
void Polynomial::initialize(int c, int e)
{ 
	vector<term> poly;
	int (c, e);
	while(cin>> (c, e))
	{
 		term.push_back(c, e);
 	}
} 
int Polynomial::get_term()
{
	return term.size();	
}
istream& operator>> (istream& stream, Polynomial& poly)
{
	const char SENTINEL = 'x';
	int co;
	int expo;
	
	poly.term.erase (poly.term.begin(), poly.term.end());
            do
           {
		stream>> co, expo;
		poly.term.push_back (co, expo); 
	}
	while (coefficient!= SENTINEL);
}
ostream& operator<< (ostream& stream, Polynomial& poly)
{
	for (int i = 0; i < poly.term.size(); i++)
                stream << poly.term [i];
    return stream;
}
void Polynomial::sort()
{
	//how do i have it sort the exponents as it is being entered 
}
Polynomial operator+(Polynomial& p1, Polynomial& p2);
{
	Polynomial p3;
	int sum;

	vector<term>::const_iterator iter;
	iter = poly.begin();
	vector<int>::const_iterator iter2;
	iter2 = p2.poly.begin();
	
// i don't know how to make it compare exponents and then add the coefficients with like exponents. i think what i've done here is just compare 2 terms and not the exponent part of the term
   
 for (i = 0; i<poly.size(); i++)
		if (*iter == *iter2)
			sum = poly[i] + p2.poly[i]
		iter++
		iter2++
	return p3;
}

I don't have a main yet. Thank you once again and am very new to coding in general and i have a hard time putting things together or verifying if my logic or syntax makes sense

Start small and work your way up. For example, you could start with just creating and displaying a polynomial. Then you could add a method to read a polynomial. Then add polynomials. Etc. Each step of the way test it out in main(). Once you are done, you can move the stuff into separate .h and .cpp files.

The introduction of a term class was brilliant! Good job!

I removed the initialize() method (it won't work and you don't need it).
The sort() method is not a constructor.
I've also renamed get_term() to number_of_terms(), as a more descriptive name.
Don't forget to end a struct or class type with a semicolon.

Also, indentation and formatting will help considerably when you read your code. For example:
[code=C++]

//------------------------------------------------
// The stuff that follows would go in your Poly.h
// file when you are done testing it

#include <iostream>
#include <vector>
using namespace std;

struct term
{
	int co;
	int expo;
};

class Polynomial
{
	friend istream& operator>> (istream& stream, Polynomial& poly);
	friend ostream& operator<< (ostream& stream, Polynomial& poly);

	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
		Polynomial operator+( const Polynomial& p );

		// returns the number of terms in the polynomial
		int number_of_terms();
};

//------------------------------------------------
// The stuff that follows would go in your Poly.cpp
// file when you are done testing it

// Try to keep things in the same order as above.

istream& operator>> (istream& stream, Polynomial& poly)
{
	// This needs serious help. See below.
	return stream;
}

ostream& operator<< (ostream& stream, Polynomial& poly)
{
	for (int i = 0; i < poly.number_of_terms(); i++)
		// This next line also needs help. See below.
		stream << poly.poly[i].co;
	return stream;
}

Polynomial::Polynomial()
{
	reset();  // Nice!
}

void Polynomial::sort()
{
	// Q. how do i have it sort the exponents as it is being entered
	// A. there is nothing being entered. You have all the data listed
	//    in the poly vector. You need to sort that.
}

void Polynomial::reset()
{
	// This is a bonus. I would have pointed you to the clear()
	// function in any case, so I just fixed your code here.
	poly.clear();
}

int Polynomial::number_of_terms()
{
	return poly.size();
}

Polynomial Polynomial::operator+( const Polynomial& p )
{
	Polynomial result;

	// See below

	return result;
}

//------------------------------------------------
// What follows is for testing your poly class.
//
// The first thing you should check is that everything
// compiles without any errors or warnings.
//
// Then, use main() to test that everything works
// the way it ought to. (Fix the things that don't.)
//
// Once done, add __one__ new thing at a time
// to your Polynomial class.

int main()
{
	// The polynomial we'll test with
	Polynomial p;

	// Make the polynomial = 4x^3 - 2x^2 + 5
	term t;

	t.co = 4;
	t.expo = 3;
	p.poly.push_back( t );

	t.co = -2;
	t.expo = 2;
	p.poly.push_back( t );

	t.co = 5;
	t.expo = 0;
	p.poly.push_back( t );

	// Display the polynomial
	cout << "The polynomial is: " << p << endl;

	cout << "\nThe number of terms in the polynomial is "
	     << p.number_of_terms() << endl;

	// Test the sort
	// (First, we'll add a term out of order)
	t.co = 1;
	t.expo = 5;
	p.poly.push_back( t );
	// (Display it out of order)
	cout << "\nAdded the term x^5: " << p << endl;
	// (Sort and display it)
	p.sort();
	cout << "In cannonical form: " << p << endl;

	// Add it to itself and display the result
	p = p + p;
	cout << "\nAdded to itself it is: " << p << endl;


	cout << "\nAll done." << endl;

	return 0;
}

OK, there were several spots where it said "see below". First, compile and run the program so you can get a better idea of I'm doing for you here.

operator>>
Heh, I don't want to mess with this at the moment. Work on the other things first.

operator<<
Line 57, 58: The computer has no idea how to display a term struct, so compilation would fail on this line. (I changed it to display the coefficient so that it would compile, but you still need to fix it.)

You will need to keep in mind several things:

  • The term only stores/holds two integer numbers, but you need to display something of the form + 4x^9 or - 7x^2
  • What if the exponent is 1 or 0? It would be nice to see 7x and 7 , respectively.
  • What if the coefficient is negative?

You will probably want to make a compound statement (that is, use curly braces { }) and use more than one stream << statement.

sort()
There is nothing being input or output in sort(). You only need to rearrange the order of the terms so that the largest exponent is first, the next largest next, etc.

Also, what should happen if you have two terms with the same exponent?

operator+
This operator is different than the << and >> operators, because it is a member of the Polynomial class, not a friend.

So, when you say something like the following p3 = p1 + p2; It is the same as saying: p3 = p1.operator+( p2 ); You will have to read your class notes over again to see the difference between member and friend operators. If you want, you can just make the + operator a friend function and do it like you were planning to.


Finally (whew, he's finally going to stop!), there is a bug in your program. The assignment operator is not overloaded. You need to do that.

Hope this helps, good luck, and post back as when you get stuck again.

Comments
Thnx for the continued support and patience!
excellent response

I don't know if i would have been able to get this far if it wasn't for your guidance Duoas and the help with my methods from a friend. I read your reply and sought to correct my mistakes where you addressed.

I don't understand what you mean when you say "The assignment operator is not overloaded. You need to do that."

Also, as far as my operator+ not being a friend. I changed it into a friend function because thats how i've always worked with them and have previous examples to go back to. And yes i do need find something that tells me the difference between a member function and a friend function.

Though it isn't finished, i get this error message everytime i compile: poly.h(25) : error C2208: 'std::vector<_Ty>' : no members defined using this type operator>>
What i was trying to do was have the user be able to input the polynomial terms and have it recognize when the user enters the sentinel value and stops. I still don't 100% understand what this operator is for besides defining a sentinel value

My professor NEVER explains anything well. The professor assumes i have a previous background with these things so am forced to interpret everything and give it a meaning or seek help elsewhere and hope i understand.

Attached is what i've done with the program so far.

My main is pretty rough, i don't know if i'm pointing to the right functions or not.

Oh and i want to say thank you so much again for the continued help.

Attachments
#include "Poly.h" 
#include <iostream> 

using namespace std;

istream& operator>> (istream& stream, Polynomial& poly)
{
	// This needs serious help
	
	return stream;
}
 
ostream& operator<< (ostream& stream, Polynomial& poly)
{
	for (int i = 0; i < poly.number_of_terms(); i++)
		// This next line also needs help.
		if (poly.expo=0)
		stream << poly[i].co << "\t";
		if (poly.expo=1)
		stream << poly[i].co <<poly[i].var<< "\t";
		else
		stream << poly[i].co <<poly[i].var+"^"<<poly[i].expo<< "\t";

	return stream;
}
 
Polynomial::Polynomial()
{
	reset();  
}
 
void Polynomial::addTerm(term t)
{
	it= poly.begin();
	if(poly.empty())
		poly.insert(poly.begin(), t);
	else if( t.expo < poly.last().expo)
			{
					poly.push_back(t);
			}
	else if( t.expo > poly.front().expo)
			{
					poly.insert(poly.begin(), t);
			}
	else if
	{
		for( int x = 0; x<poly.size(); x++)
		{
			if(t.expo==(poly[x].expo))
			{

				if (t.var==(poly[x].var))
				{
					poly[x].co+=t.co; 
				}
				else
				{
					int i = 0
					do{
					it++;
					i++;
					if(i==x)
					poly.insert(it, t);
					}while( i<x)
				}

			}
		}
	}


}
 
void Polynomial::reset()
{
	poly.clear();
}
 
int Polynomial::number_of_terms()
{
	return poly.size();
}
 
Polynomial operator+( const  Polynomial& p1, const Polynomial& p2 )
{
	Polynomial result;
	for{int x=0, x<p1.size(); x++)
	{
		result.addTerm(p1.poly[x]);
	}

	for{int y=0, y<p2.size(); y++)
	{
		result.addTerm(p2.poly[x]);
	}
	// need help
 
	return result;
}
#ifndef poly
#define poly
#include <iostream>
#include <vector>

using namespace std;

struct term
{
	int co;
	int expo;
	char var;

};
 
class Polynomial
{
	friend istream& operator>> (istream& stream, Polynomial& poly);
	friend ostream& operator<< (ostream& stream, Polynomial& poly);
 
	public:
 
		// The list of terms in the polynomial
		// (not necessarily ordered)
		vector<term> poly;
		vector<term>::iterator it;
 
		// 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+( Polynomial& p1, 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.  Sum"<<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 x to stop"<<endl;
  cin>>p2;

  result = p + p2;
  cout<<"Values for added polynomial are:"<<endl;
  cout<<"Number of Terms:  "<<result.size()<<endl;
  cout<<"Sum:  "<<result.addTerm( )<<endl;
}
int main (void)
{
	int choice;
	int co, expo;
	char var;

	//declare a Polynomial
	Polynomial p;
	p.reset();

	do {
	  //print menu
	  menu();
	  cin>>choice;

	  switch (choice) {
		case 1 : cout<<endl<<"Enter The coefficient> ";
				cin>>co;
				p.poly.addTerm(co);
				cout<<endl;
				cout<<endl<<"Enter Variable> ";
				cin>>var;
				p.poly.addTerm(var);
				cout<<endl;
				cout<<endl<<"Enter Exponent> ";
				cin>>expo;
				p.poly.addTerm(expo);
				cout<<endl;
				break;

		case 2 : p.reset();
				cout<<endl<<"Polynomial reset"<<endl;
				break;

		case 3: cout<<endl<<"Sum is "<<p.result()<<endl;
				break;

		case 4: cout<<endl<<"Number of Terms is "<<p.number_of_terms()<<endl;
				break;
		case 5: cout<< "The polynomial is: " << poly << endl;
				break;
		case 6: cout<<endl<<"Thanks and goodbye."<<endl;
				break;

		default :  cout<<endl<<"Invalid command.  Try again."<<endl;
	  }

	} while (choice != 5);
}

iamthwee, how do you get more than one coefficient per term? His struct is fine as is.

Also, the sort() method is not redundant. I called it "normalize", but the thing it does is about the same. By having a routine that normalizes/sorts the polynomial, other activities become a lot easier.

orangejuice2005, you'll have to give me a day to look over your latest. My brain needs sleep now...

iamthwee i was trying to have the terms sorted as they entered into the vector as well as add like terms

duoas its ok! I wasn't going to be able to work on it today anyways becuase i had to work the whole day and i needed to work on a paper when i got back.

>iamthwee, how do you get more than one coefficient per term

That's just the point, the struct it isn't based on one term.

>By having a routine that normalizes/sorts the polynomial, other activities become a lot easier.

Again, the whole sorting becomes redundant if you follow the structure in the link I provided.

Duoas, there are many ways to solve one problem. I'm not deliberately trying to say your method wrong. It's not.

iamthwee, you've missed the point.

The OP's Polynomial class is based on a vector of term structs. (He made this change in his second post.) Each term in a polynomial (which he represents with the struct term) has exactly one coefficient and one exponent.

I am full aware that there are many ways to solve this problem. The problem with the link you provided is two-fold:

  1. it doesn't match the structure the OP uses; the link uses a fixed array of terms, the OP does not.
  2. it gives away an answer for free; if the OP were to use it he would learn nothing (and as a professor I would fail him for cheating)

I wasn't criticizing you. I would rather help the OP figure out his problem in his own way rather than re-design his code for him. That's all.

>The OP's Polynomial class is based on a vector of term structs. (He made this change in his second post.)...has exactly one coefficient and one exponent.

So what if he did. If I'm reading the previous post correctly, there was no mention he needs to EXPLICITLY make the struct have one coeff and one exponent.

>it doesn't match the structure the OP uses;

See above point.

>the link uses a fixed array of terms, the OP does not.

Not quite, the java link uses the new operator to for dynamic array usage.

>it gives away an answer for free
Perhaps, although you could argue the conversion from java to c++ would help him learn a lot in itself.

>I wasn't criticizing you. I would rather help the OP figure out his problem in his own way rather than re-design his code for him. That's all.

Sure. That's what a good answer should strive to achieve. Don't feel you need to justify yourself just because I disagree slightly, you don't. (We had a similar conversation on the blender forums :cool:) Your help is excellent and congruent over different forums. I'll let you carry on.

Here is my input stream overload. The sentinel value is x or X and while the user input isn't x or X, the input(pterm) is added to the vector as a term...did i do it right?

i just learned about cin.peek and isspace so i used that here

istream& operator>> (istream& stream, Polynomial& poly)
{
	int pterm;

    while (stream && (stream.peek( ) != 'x'|| 'X'))
    {
	if (isspace(stream.peek( )))
	    stream.ignore( );
	else
	{
	    stream >> pterm;
	    poly.poly.insert(poly.begin(), pterm);
	}
    }
    stream.ignore( );
	
	return stream;
}

Getting input is probably going to be the toughest part of the assignment. For each term, you have to read something that looks like this (where green is optional) [B]-[/B] [I]12[/I] [B]x[/B] [B]^[/B][I]-2[/I] So, you might want to peek to see if there is a '-' or '+' sign, and make note of it. If there is, read it.

Then try to read a number.

Then the x.

Then check to see if there is a '^'. If so, read it and another number.

Now you have your two numbers. Adjust the first based on whether or not there was a '-' sign in front of it.

Stick your two numbers into a term struct, and push_back() the struct on your poly vector.

For trying to read those numbers, you may want to check out the fail() and clear() members of the input stream.

Hope this helps.

Thanks for breaking it down for me Duoas, i'll see if i can figure it out and do it and then show you what i came up with!

I can't seem to come up with something that suffice. Here is what i got now.

istream& operator>> (istream& stream, Polynomial& poly)
{
	struct term;

    while (stream && (stream.peek( ) != 'x'|| 'X'))
    {
	if (isspace(stream.peek( )))
	    stream.ignore( );
	else
	{
	    if (stream.peek() == '-' || '+')
		{
			// you told me what to do with the '-' and '+' signs 
			// but how do i translate  that into code
		}

		stream>> term.co;
		stream>> term.var;

		if ( stream.peek() = '^')
		{
		      stream.ignore() // read it and do what? this doesn't do anything as input
		}
		stream >> term.expo;

	    poly.poly.push_back(term);
	}
    }
    stream.ignore( );
	
	return stream;
}

Did i place the input in the struct correctly? and i read up on fail() and clear() members of the input stream but isn't that for catching wrong input and handling it? I want to get this input overload right first then i would turn my atttention to worrying about whether or not i was given the correct input.

A good place to start actually is to force the input to take a certain form.

For example, you could say that input must be of the form: [B]-[/B][I]42[/I] [B]x ^[/B][B]-[/B][I]3[/I] where the '-' signs are optional (of course).

You could then just read assuming information is present:

istream& operator>> (istream& stream, Polynomial& poly)
{
    term t;  // You must declare a variable here...

    if (stream.peek() == '+') stream.get();  // skip any '+'s

    stream >> t.co;    // read the coefficient
    stream.get();      // read the 'x'
    stream.get();      // read the '^'
    stream >> t.expo;  // read the exponent

    poly.poly.push_back( t );

    return stream;
}

Now you can go back and add in stuff to check whether or not something is present.
For example, you can modify it to check to see if an exponent is there before trying to read one.
You can check to see whether an 'x' is there before trying to read it.

Then you can type terms of the form 3x instead of 3x^1 and -7 instead of -7x^0 .

Oh yeah, don't forget that in C++ you don't need to say struct term t; you can just say term t; but you must always name a variable. "term" is a type. "t" is a variable. Don't mix them.

Hope this helps.

Thanks i think i understand this a little better now. For clarification cin.get() just reads the next input value and places it in a cup somewhere as if to say i was expecting such an input but nothing is to be done with it?

Here is what i did with the input overload you provided. I ran through all these scenarios and possibilities in my head (like since each input is being read, what happens if i come across a negative sign? is that a char by itself or is it considered to be apart of an integer) and went through many possible ways i could do this, but in the end, your way was much easier for me.

istream& operator>> (istream& stream, Polynomial& poly)
{
    term t; 
	bool symbol = true;
	while (stream>> !=';')
	{
		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;
		}
			poly.poly.push_back( t );
	}
    return stream;

}

I went ahead and compiled the program....i made some changes to my main after going back and checking for noob errors , but i still get the same error.

poly.h(25) : error C2208: 'std::vector<_Ty>' : no members defined using this type
1>        with
1>        [
1>            _Ty=term
1>        ]

Thnx again....my professor threw me into the water with this one but i choose not to drown.

Tell me if the overload will work or will suffice plz? Thnx Duoas

Yes, cin.get() just reads one character, and throws it away (well, returns it, but you didn't save the return value).

Your input function looks much better.

As to the error: I don't know. I don't have your most recent code so I can't investigate on my own. But I think that the problem is a variation on the last problem...

Am going to attach my header file, cpp, and main file to this post so you can take a look at them ok? I don't know what the error means.

Attachments
#include "Poly.h" 
#include <iostream> 

using namespace std;

istream& operator>> (istream& stream, Polynomial& poly)
{
    term t; 
	bool symbol = true;
	while (stream>> !=';')
	{
		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;
		}
			poly.poly.push_back( t );
	}
    return stream;

}
 
ostream& operator<< (ostream& stream, Polynomial& poly)
{
	for (int i = 0; i < poly.number_of_terms(); i++)
		// This next line also needs help.
		if (poly.expo=0)
		stream << poly[i].co << "\t";
		if (poly.expo=1)
		stream << poly[i].co <<poly[i].var<< "\t";
		else
		stream << poly[i].co <<poly[i].var+"^"<<poly[i].expo<< "\t";

	return stream;
}
 
Polynomial::Polynomial()
{
	reset();  
}
 
void Polynomial::addTerm(term t)
{
	it= poly.begin();
	if(poly.empty())
		poly.insert(poly.begin(), t);
	else if( t.expo < poly.last().expo)
			{
					poly.push_back(t);
			}
	else if( t.expo > poly.front().expo)
			{
					poly.insert(poly.begin(), t);
			}
	else if
	{
		for( int x = 0; x<poly.size(); x++)
		{
			if(t.expo==(poly[x].expo))
			{

				if (t.var==(poly[x].var))
				{
					poly[x].co+=t.co; 
				}
				else
				{
					int i = 0
					do{
					it++;
					i++;
					if(i==x)
					poly.insert(it, t);
					}while( i<x)
				}

			}
		}
	}


}
 
void Polynomial::reset()
{
	poly.clear();
}
 
int Polynomial::number_of_terms()
{
	return poly.size();
}
 
Polynomial operator+( const  Polynomial& p1, const Polynomial& p2 )
{
	Polynomial result;
	for{int x=0, x<p1.size(); x++)
	{
		result.addTerm(p1.poly[x]);
	}

	for{int y=0, y<p2.size(); y++)
	{
		result.addTerm(p2.poly[x]);
	}
	// need help
 
	return result;
}
#ifndef poly
#define poly
#include <iostream>
#include <vector>

using namespace std;

struct term
{
	int co;
	int expo;
	char var;

};
 
class Polynomial
{
	friend istream& operator>> (istream& stream, Polynomial& poly);
	friend ostream& operator<< (ostream& stream, Polynomial& poly);
 
	public:
 
		// The list of terms in the polynomial
		// (not necessarily ordered)
		vector<term> poly;
		vector<term>::iterator it;
 
		// 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+( Polynomial& p1, 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.  Sum"<<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"<<endl;
  cin>>p2;

  result = p + p2;
  cout<<"Results for added polynomial are:"<<endl;
  cout<<"Number of Terms:  "<<result.size()<<endl;
  cout<<"Sum:  "<<result<<endl;
}
int main (void)
{
	int choice;
	term t;

	//declare a Polynomial
	Polynomial p;
	p.reset();

	do {
	  //print menu
	  menu();
	  cin>>choice;

	  switch (choice) {
		case 1 :cout<<endl<<"Enter the first polynomial term(Input must be of the form: 4x^2)";
				cin>>p;
				p.poly.addTerm();
				break;

		case 2 : p.reset();
				cout<<endl<<"Polynomial reset"<<endl;
				break;

		case 3: cout<<endl<<"Sum is "<<p.result()<<endl;
				break;

		case 4: cout<<endl<<"Number of Terms is "<<p.number_of_terms()<<endl;
				break;
		case 5: cout<< "The polynomial is: " << poly << endl;
				break;
		case 6: cout<<endl<<"Thanks and goodbye."<<endl;
				break;

		default :  cout<<endl<<"Invalid command.  Try again."<<endl;
	  }

	} while (choice != 6);
}

You've got a name collision with the preprocessor.

At the top, you said #define poly Then below you say: vector<term> poly; which becomes: vector<term> ; Hence the grief.

In general, make sure that you guard your include files by using the same name as the file, but in all caps: #ifndef POLY_H #define POLY_H ...


You've got a lot of other errors in there too... Take them one at a time and try to see where you've made an error. You'll get through it.

The very first error, though, I'll help you with. Poly.cpp, line 10: you are trying to do something you can't: while (stream>> != ';') This is invalid syntax.

I'll show you the right way.

  1. You aren't testing if you are at EOF.
  2. You should peek for ';', because if it isn't you don't want to have actually read the character...
  3. Once you find ';', you'll want to read it.

So, something like the following might help:

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
      }
      ...  // normal stuff follows
  }

Hope this helps.

Thanks Duoas that fixed my problem.

And as i continued through and errors, i realized i had to completely redo some things and one of those things is my sort method.

I am trying to apply the sort() algorithm on my vector of structs. I want the vector to be sorted according to one of the struct fields, the exponent. I tried doing it this way similiar to an example i found somewhere on the internet.

Am tryin to define a comparison function and then send it to the sort function as a parameter
Poly.h

void sort(); // sort method

Poly.cpp

void Polynomial::sort() 
{
	sort(poly.begin(), poly.end(), operator<) 
}
bool Polynomial::operator< (const term& other_term) const
{
	 return term.expo < other_term.expo;		
}

as you can see, its very poorly constructed, am planning on asking my professor tmr in class. But i wanna ask her other questions so hears hopin u see this before then

Hey jacki, thnx for the suggestions and reference but we just started learning about that data structuer, the link list, and it does seem more ideal to use it for this problem since its way more flexible than arrarys or vectors......am using a vectors to get the job done b/c it's what am most comfortable with at the moment.

Duoas do u mind checking my login for my operator + overload?

Polynomial operator+( const  Polynomial& p1, const Polynomial& p2 )
{
    Polynomial result;
    

    for( int i = 0; i<poly.size(); i++)
        {
            if(p1[i].expo == p2[i].expo)
            {
                result.push_back(p1[i].co + p2[i].co);
            }
            else
            {
                result.push_back(p1[i]);
                result.push_back(p2[i]);
            }
            i++
        }
    return result;
}

Thnx! I got one more day left on this assignment so am working on it vigorously

Updated my + operator, tell me what you think

Polynomial operator+( const  Polynomial& p1, const Polynomial& p2 )
{
    Polynomial result;
    term t;

    for( int i = 0; i<p1.size(); i++)
        {
            for (int j=0; j<p2.size(); j++)
	    {
		if(p1[i].expo == p2[j].expo && p1[i].var == p2[j].var)
            	{
                	t.co = p1[i].co + p2[j].co;
			t.var = p1[i].var;
			t.expo = p1[i].expo;	
			result.push_back(t);
            	}
            	else
	
		{
                	result.push_back(p1[i]);
                	result.push_back(p2[j]);
            	}
            }
	}
    return result;
}

I changed my operator + overload again but i think its poorly constructed and i keep getting these errors and i don't know how to fix them.

1\poly.cpp(45) : warning C4018: '<' : signed/unsigned mismatch
1\poly.cpp(82) : warning C4018: '<' : signed/unsigned mismatch
1\poly.cpp(84) : warning C4018: '<' : signed/unsigned mismatch
1\poly.cpp(86) : error C2100: illegal indirection
1\poly.cpp(86) : error C2100: illegal indirection
1\poly.cpp(86) : error C2100: illegal indirection
1\poly.cpp(86) : error C2100: illegal indirection
1\poly.cpp(88) : error C2100: illegal indirection
1\poly.cpp(88) : error C2059: syntax error : '.'
1\poly.cpp(89) : error C2039: 'r' : is not a member of 'term'
1\poly.h(9) : see declaration of 'term'
1\poly.cpp(89) : error C2059: syntax error : '.'
1\poly.cpp(90) : error C2039: 'r' : is not a member of 'term'
1\poly.h(9) : see declaration of 'term'
1\poly.cpp(90) : error C2059: syntax error : '.'
1\poly.cpp(91) : error C2039: 'result' : is not a member of 'term'
1\poly.h(9) : see declaration of 'term'
1\poly.h(9) : see declaration of 'term'
1\poly.cpp(91) : error C2228: left of '.push_back' must have class/struct/union
1\poly.cpp(95) : error C2676: binary '[' : 'const Polynomial' does not define this operator or a conversion to a type acceptable to the predefined operator
1\poly.cpp(96) : error C2676: binary '[' : 'const Polynomial' does not define this operator or a conversion to a type acceptable to the predefined operator
1\poly.cpp(111) : error C2065: 'expo' : undeclared identifier

Here is my code

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]);
		    }
                 }
	     } 
	}while (it !=p1.poly.end() || it2 !=p2.poly.end());

	return result;
}

I apologize, I'm kind of jumping into this thread without having read the rest of it, but you're using iterators wrong here:

if(*it->expo == *it2->expo && *it->var == *it2->var)

The *'s are unnecessary. To access a member using an iterator, just do it->member .

Also, here:

r.co = *it->co + *it2->.co;
r.var = *it->.var;
r.expo = *it->.expo;	
result.poly.push_back(r);

Get rid of the *'s again, and also the periods after the dereference operator ( -> ).

Thank you joeprogrammer! those little corrections actually got rid of most of my errors!

I also realized i forgot to increment the iterators.

I have another issue. I'm trying to sort the elements in a vector according to one of the fields of my struct (the exponent)

I figured i'll just implement the STL's sorth algorithm and am able to do this as long as i have a less than operator defined right? Here is what i did:

void Polynomial::sort()
{
	poly.begin(), poly.end();
}

bool Polynomial::operator< (const term& other_term) const
{
	return expo < other_term.expo; 
}

But i get this error: 1\poly.cpp(113) : error C2065: 'expo' : undeclared identifier I would appreciate any input or help.

>I figured i'll just implement the STL's sorth algorithm and am able to do this as long as i have
>a less than operator defined right?
You don't 'implement' it, you just make sure that the '<' operator produces the desired results, which in this case would consist merely of overloading the '<' operator.

>But i get this error
Well, to me it looks like the compiler doesn't know what 'expo' is, thus the 'undeclared identifier' error. Is expo a member of Polynomial ? Why does your overloaded '<' function for Polynomial take term as a parameter?

expo is one of the data fields for my term structure.

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?

I have my poly.h file uploaded on page 2. If you don't mind taking a look at it, then you'd be able to see how i got things set up.

This question has already been answered. Start a new discussion instead.