So i have..
struct Polynomial{
deque<long> coefs;
long degree;
Polynomial(initializer_list<long> co_list);
Polynomial(deque<long> & co_list);
Polynomial();
string poly_to_string();
Polynomial add(Polynomial rhs);
Polynomial mult(Polynomial rhs);
Polynomial mult(long factor);
}
For theese methods I have to :
Polynomial(initializer_list cfs ). Initialize the instance using an initializer list of coefficients.
-order is the highest power goes first, lowest last
-coefs and degree updated.
Polynomial(deque cfs). Initialize the instance using a vector of coefficients. -order is the highest power goes first, lowest last
-coefs and degree updated.
Then I do methods to add/multiple/factor the polynomial, which I can do, just not sure what
Polynomial(initializer_list<long> co_list);
Polynomial(deque<long> & co_list);
are suppose to do / how to start them..
Also, how would i would I start the function to return
Polynomial.degree
To return a long value?
Those two functions are the constructors for the type. They tell the compiler how to set up a Polynomial object so that it's ready for members to be called. They're most easily understood like this:
struct Polynomial{
deque<long> coefs;
long degree;
Polynomial(initializer_list<long> co_list);
Polynomial(deque<long> & co_list);
};
Polynomial::Polynomial(initializer_list<long> co_list)
{
//at this point, the members are created, but have no values
//so we assign values to the members
coefs.assign(co_list.begin(), co_list.end());
degree = co_list.size();
}
int main()
{
Polynomial mypoly = {3, 4, 5};
//creates a Polynomial variable from an initializer list
//the compiler runs the constructor function automatically
//so now it's members are all properly set, and we can run other functions
mypoly.do_thing();
}
However, as shown above, the Polynomial constructor constructs the two members, and then executes the function that assigns them values. We can make this even better by constructing them directly with the intended values:
Polynomial::Polynomial(initializer_list<long> co_list)
:
coefs(co_list.begin(), co_list.end()), //constructed directly
degree(co_list.size())
{
//they already have the needed values, don't need to do anything more
//to finalize the construction
}
Related
This question already has answers here:
Variable number of arguments in C++?
(17 answers)
Closed 11 months ago.
i have this question:
You will implement a polynomial class that uses a dynamic array to store the polynomial's coefficients.
The Polynomial class has two private members variables: a dynamic array to store the
coefficients and the degree of the polynomial like so:
(private:
double *coef; // Pointer to the dynamic array
int degree; // the polynomial degree)
1.Write the constructors permitting the initialization of simple polynomials of the following way:
i. Polynomial p1(3,1); // polynomial of degree 1 p1 = 3 x+1
ii. Polynomial p2(1,4,2); // polynomial of degree 2 p2 = x2+4x+2
iii. Polynomial p3(1,3,3,1); // polynomial of degree 3 p3 = x3+ 3x2 + 3x +1
that is the question.
these constructors are being handed the coefficients but the number of coefficients is chosen by the user, how do i make such constructor(s)??
and i cant put a limit on the degree of the polynomial the user wants to enter(if this were the case, i could put default values that are zero so that if he doesnt give all coefficinets, the rest of coefficients will be zero)
is the dynamic array member going to help in this problem?
I suggest creating a struct Term:
struct Term
{
int coefficient;
int power;
};
A polynomial, by definition is a container (or sum) of terms:
class Polynomial
{
public:
std::vector<Term> terms;
Polynomial(int coef1, int constant1);
}
In the above class, the constructor will create two terms:
Polynomial::Polynomial(int coef1, int constant1)
{
Term t1;
Term c;
t1.coefficient = coef1;
t1.power = 1;
c.coefficient = constant1;
c.power = 0;
terms.push_back(c);
terms.push_back(t1);
}
The next constructor, in your requirements, creates 3 terms:
Polynomial::Polynomial(int coef1, int coef2, int constant1)
{
Term t1 = {coef1, 2};
Term t2 = {coef2, 1};
Term constant_term = {constant1, 0};
terms.push_back(constant_term);
terms.push_back(t2);
terms.push_back(t1);
}
One of the theorems of addition is that the terms can be in any order. You can change the order that you append them to the container so you print them in common order (highest exponent term first).
Array of Coefficients
In the requirements, there is double * coef which is supposed to be an array of coefficients (one for each term).
Here's one example of a constructor:
Polynomial::Polynomial(double coef1, double constant)
{
degree = 1;
coef = new double[2]; // 2 terms.
coef[0] = coef1;
coef[1] = constant;
}
The other constructors are similar to the above one.
Remember, your destructor should contain delete[] coef;.
This question already has answers here:
Rationale of enforcing some operators to be members
(2 answers)
What are the basic rules and idioms for operator overloading?
(8 answers)
Closed 7 years ago.
I am working with Graphs, and writing code some well known algorithms. Currently I am working on the Dijkstra Algorithm.
So, I have made my own Heap class which works as a min-priority queue for the implementation of the Dijkstra algorithm. Since, in the Dijkstra algorithm, you need to update the distance of a vertex (which is already in the heap), from the source vertex in the Graph, if its distance is less than it's current distance, and then accordingly adjust the values in a Heap.
For this, I need to keep an int position[] array to keep a track of the positions at which the elements are currently in the Heap
This is my Vertex Class ::
class Node{
public:
int data;
int weight;
.....
friend int& operator [](int *a, Node i) {
return a[i.data];
}
};
My minPriorityQueue class ::
template <typename t>
class minPriorityQueue {
int size, currentPosition;
int *position;
t *data;
bool (*compare)(t data1, t data2);
public:
minPriorityQueue(int size, bool (*func1)(t data1, t data2), int *position) {
this->size = size;
currentPosition = 1;
data = new t[size];
compare = func1;
this->position = position;
}
........
void swapPositionValue(int parent, int temp) {
int tempPosition = position[data[parent]];
position[data[parent]] = position[data[temp]];
position[data[temp]] = tempPosition;
}
......
};
Since my vertices are 0,1,2,3, ... So, I try to overload the []operator of my Vertex class so that it returns me the data of the current vertex (which is one from 0,1,2,3 ..., so I can use it to access that index of the position array.
I get the compilation error :: error: 'int operator[](int*, graph::Vertex)' must be a nonstatic member function
Well, since I get this error I assume that it must have been specified in the standard that I cannot overload the []operator using a friend function, but why I cannot do it?? Does it lead to any ambiguity? I don't see what can be ambiguous in what I am currently using.
Secondly, is there any way I can swap the values in my position array? My minPriorityQueue class is a generic class which I am using at several other places at my code as well. In the function swapPositionValue if I change my swap statements to this ::
int tempPosition = position[data[parent].data];
position[data[parent].data] = position[data[temp].data];
position[data[temp].data] = tempPosition;
Then the whole idea of "generic" priority queue will be sacrificed! Since, it won't work with other classes!
Is there a way that I can achieve this functionality??
EDIT1 :: The complete Code :: http://ideone.com/GRQHHZ
(Using Ideone to paste the code, Because the code is still very large, containing 2 classes)
This is what I am trying to achieve :: http://www.geeksforgeeks.org/greedy-algorithms-set-7-dijkstras-algorithm-for-adjacency-list-representation/
(I am just using the algorithm)
Explanation of what is the functionality of operator[]::
In my Dijkstra implementation all the nodes are initially inserted into the Heap, with the start node, having the weight = 0, and all the other nodes with weight = INFINITY (which means I cannot reach the vertices) so start vertex is the topmost element of the heap! Now when I remove the topmost element, all the Node that have a path from the removed Node will get modified, their weight will be modified from INFINITY to some finite value. So, I need to update the Nodes in the Heap, and then I need to move them to their correct positions, according to their new weights!! To update their weights, I need to know at what position are the Nodes located in the Heap, and the position is decided by the data of the Node. So, overloading the []operator was just a small way out for me, so that when I do position[Node], I can access position[Node.data].
Why this is not a duplicate:: The linked question is a broad operator overloading post, it just mentions 1 point where it states that []operator can only be overloaded with member functions and not otherwise, does not state why! And this is a specific problem I am facing where I do not want to sacrifice the generic property of my self made Heap, and use it for the Dijkstra as well.
EDIT2 :: While writing this explanation I realize I had made a big mistake in my overloaded function. I have changed it! Please check it. Probably it makes more sense now. Apologies!!
The overloaded function now looks like ::
friend int& operator [](int *a, Node i) {
return a[i.data];
}
EDIT3 :: In implement my Graph class with Adjacency Matrix, and it is a boolean 2D array, because my current implementation is for Unweighted graphs, and accordingly the shortest path becomes the least number of edges traversed! (Just in case that mattered!)
Thanks for reading all of this huge question, and for any help! :)
Here is the problem I am trying to solve:
Using dynamic arrays, implement a polynomial class with polynomial addition,
subtraction, and multiplication. Discussion: A variable in a polynomial does nothing but act as a placeholder for
the coefficients. Hence, the only interesting thing about polynomials is the array
of coefficients and the corresponding exponent. Think about the polynomial
xxx + x + 1
Where is the term in x*x ? One simple way to implement the polynomial class is to
use an array of doubles to store the coefficients. The index of the array is the
exponent of the corresponding term. If a term is missing, then it simply has a zero
coefficient.
There are techniques for representing polynomials of high degree with many missing
terms. These use so-called sparse matrix techniques. Unless you already know
these techniques, or learn very quickly, do not use these techniques.
Provide a default constructor, a copy constructor, and a parameterized constructor
that enables an arbitrary polynomial to be constructed.
Supply an overloaded operator = and a destructor.
Provide these operations:
polynomial + polynomial, constant + polynomial, polynomial + constant,
polynomial - polynomial, constant - polynomial, polynomial - constant.
polynomial * polynomial, constant * polynomial, polynomial * constant,
Supply functions to assign and extract coefficients, indexed by exponent.
Supply a function to evaluate the polynomial at a value of type double .
You should decide whether to implement these functions as members, friends, or standalone functions.
This is not for a class, I am just trying to teach myself C++ because I need it as I will start my graduate studies in financial mathematics at FSU this fall. Here is my code thus far:
class Polynomial
{
private:
double *coefficients; //this will be the array where we store the coefficients
int degree; //this is the degree of the polynomial (i.e. one less then the length of the array of coefficients)
public:
Polynomial(); //the default constructor to initialize a polynomial equal to 0
Polynomial(double coeffs[] , int nterms); //the constructor to initialize a polynomial with the given coefficient array and degree
Polynomial(Polynomial&); //the copy constructor
Polynomial(double); //the constructor to initialize a polynomial equal to the given constant
~Polynomial() { delete coefficients; } //the deconstructor to clear up the allocated memory
//the operations to define for the Polynomial class
Polynomial operator+(Polynomial p) const;
Polynomial operator-(Polynomial p) const;
Polynomial operator*(Polynomial p) const;
};
//This is the default constructor
Polynomial::Polynomial() {
degree = 0;
coefficients = new double[degree + 1];
coefficients[0] = 0;
}
//Initialize a polynomial with the given coefficient array and degree
Polynomial::Polynomial(double coeffs[], int nterms){
degree = nterms;
coefficients = new double[degree]; //array to hold coefficient values
for(int i = 0; i < degree; i++)
coefficients[i] = coeffs[i];
}
Polynomial::Polynomial(Polynomial&){
}
//The constructor to initialize a polynomial equal to the given constant
Polynomial::Polynomial(double){
}
Polynomial::operator *(Polynomial p) const{
}
Polynomial::operator +(Polynomial p) const{
}
Polynomial::operator -(Polynomial p) const{
}
I am just wondering if I am on the right track, if there is a better way of doing this please let me know. Any comments or suggestions would be greatly appreciated.
This is not a full answer but a starting point for you. I used std::set because it keeps its elements ordered, so I implemented a functor and used for my set. Now, elements in set will be sorted based on my comparison functor. In the current implementation, terms will be ordered in descending order in terms of exponents.
#include<set>
struct Term
{
int coefficient;
int exponent;
Term(int coef, int exp) : coefficient{ coef }, exponent{ exp } {}
};
struct TermComparator
{
bool operator()(const Term& lhs, const Term& rhs) {
return lhs.exponent < rhs.exponent;
}
};
class Polynomial
{
private:
std::set<Term, TermComparator> terms;
public:
Polynomial();
~Polynomial();
Polynomial operator+(Polynomial p);
};
My implementation allows you to store higher order polynomials efficiently.
I have implemented addition for you. It is not in best shape in terms OOP, but you can refactor it.
Polynomial Polynomial::operator+(Polynomial p)
{
auto my_it = terms.begin();
auto p_it = p.terms.begin();
Polynomial result;
while (my_it != terms.end() && p_it != p.terms.end())
{
if (my_it->exponent > p_it->exponent)
{
result.terms.insert(*my_it);
++my_it;
}
else if (my_it->exponent == p_it->exponent)
{
result.terms.insert(Term(my_it->coefficient + p_it->coefficient, my_it->exponent));
++my_it;
++p_it;
}
else
{
result.terms.insert(*p_it);
++p_it;
}
}
//only one of the for loops will be effective
for (; my_it != terms.end(); ++my_it) result.terms.insert(*my_it);
for (; p_it != p.terms.end(); ++p_it) result.terms.insert(*p_it);
return result;
}
State of your code
You code is correct so far if by nterms you mean maximum degree of your polynomial
One simple way to implement the polynomial class is to use an array of doubles to store the coefficients.
This is what you did
The index of the array is the exponent of the corresponding term
This is why I told you you array size is equal to the degree number + 1
This way you access the coefficient (the value of your array) using its degree (which will be the key)
If a term is missing, then it simply has a zero coefficient.
Notice that in the example given, x² doesn't exist, but coefficients[2] exists in your code and is equal to 0
Provide these operations: polynomial + polynomial, constant + polynomial, polynomial + constant, polynomial - polynomial, constant - polynomial, polynomial - constant. polynomial * polynomial, constant * polynomial, polynomial * constant, Supply functions to assign and extract coefficients, indexed by exponent. Supply a function to evaluate the polynomial at a value of type double
As you mentioned it, you are missing some of those operator overload.
To go further
Here's a non-exhaustive list of what could be done to get some more experience with C++ when you will be done with this exercise:
- You could implement an expression parser (using )
- Handle more complex polynomial (i.e. x² + y² + 2xy + 1)
- Use map to store your coefficients (Map may not be considered as dynamic arrays by this exercise but could be fun for you to play with) or another data structure to get ride of your zeros in your coefficients ! (c.f. sparse matrix/arrays techniques)
Have fun in your future studies !
i have the class Team which has the attribute "Points".
In another sheet.cpp i want to change this points with some function like this:
void Result(Team a, Team b)
{
int startWerte[] = { 8, 8 };//just random start values)
std::vector< int > punkte(startWerte, startWerte + sizeof(startWerte) / sizeof(int));
points[0]=a.getpoints();
points[1]=b.getpoints();
Here follows some calculation which ends in the final values for the points stored in points2. Now i want to set them as the points of the teams, so they are stored.
a.setpoints(points[0])
b.setpoints(points[1]);
They are the correct values, but whenever this function ends the values are not stored in team.points correctly. If i do it by letting the Result function return the points2 vector to lets say vector testvector in the int main() it works. Example
vector<int> testvector;
testvector =Result(TeamA, TeamB) {//Same code than before follows
TeamA.setpoints(testvector[0];
TeamB.setpoints(testvector[1];
If i the repeat the Result-function everythin is stored correct. Is there no way to store the value for the points of the team class outside the int main ()?
I think your problem is that you are passing Team by value rather than by reference.
Change the Result method to
void Result(Team & a, Team & b)
and everything should be fine.
In this problem, the user enters in two numbers. Each number represents an integer, whose characters are stored into a list. I need to modify the + operator, so that the program will take the two list characters, change them to ints, add them, and then change it back to a char list. Its confusing I know, but hopefully the code will help clear things up:
class LongInt
{
public:
friend LongInt operator+(const LongInt& x, const LongInt& y); //This function will add the value of the two integers which are represented by x and y's character list (val).
private:
list<char> val; //the list of characters that represent the integer the user inputted
}
This is the header file for the LongInt class. There are other parts too it such as a constructor, destructor, etc, but these are the only things that matter in this case. I don't know how to go about writing the code for the operator+ definition in the implementation file. Any ideas?
You would start the function something like this:
LongInt operator+(const LongInt& x, const LongInt& y) {
// code goes here
}
This function definition would go outside the class definition (presumably in a .cpp implementation file).
Inside this function, you would add the parameters x and y using normal longhand addition (add pairs of corresponding digits, handle any carry, etc). Build up the result in a local LongInt object, and return the computed value from your operator+() function.
If it hasn't already been decided for you, you will need to decide whether the least significant digit comes first or last in your val list. Either way is valid, but one choice is likely to be easier to work with than the other (I'll let you decide which one).
If you want to convert the list of chars to an int, you can do something like this:
std::list<char> digits;
int value = 0;
for(std::list<char>::iterator it = digits.begin();
it != digits.end();
++it)
{
value = value * 10 + *it - '0';
}