C++ overloading == operator example - operator-overloading

making chess game and i can't overload == operator (think that is problem, ofc if i added correctly elements in array).
enum squerState{EMPTY, ROOK, KNIGHT, BISHOP, QUEEN, KING, PAWN};
class Board
{
public:
Board();
~Board();
friend bool operator==(const Board& lhs, const Board& rhs);
squerState stanjePolja;
squerColor bojaPolja;
pieceColor bojaFigurice;
Board* board[8][8];
};
//.ccp
Board* piece;
for(int x= 0; x < 8; x++)
{
for(int y=0; y < 8; y++)
{
piece->stanjePolja = squerState::ROOK;
piece->bojaPolja = squerColor::WHITE;
piece->bojaFigurice = pieceColor::BLACK_PIECE;
board[y][x] = piece;
}
}
//overload ==
bool operator==(const Board& lhs, const Board& rhs)
{
return lhs.stanjePolja == rhs.stanjePolja;
}
//Draw test board
void Board::drawBoard()
{
for (auto y = 0; y < 8; y++)
{
for (auto x = 0; x < 8; x++)
{
if (board[y][x] == squerState::ROOK)
{
std::cout << 'O';
}
else
std::cout << 'X';
}
std::cout << std::endl;
}
}
Problem is when i try to draw test board with ROOK's.
if (board[y][x] == squerState::ROOK)
Thanks!

In the line
if (board[y][x] == squerState::ROOK)
it looks like the type of the expression on the left-hand side is Board*, but the type of expression on the right-hand side is enum squerState. You did not define an equals operator for those types and they can't be compared by other means.
You probably want your Board class to contain an array of SquareState instances.
enum Piece { None, Pawn, ... };
enum Color { Black, White };
struct SquareState
{
Piece piece_;
Color color_;
};
struct Board
{
void drawBoard() const;
SquareState board_[8][8];
};
void Board::drawBoard() const
{
for( int i = 0; i < 8; ++i )
{
for( int j = 0; j < 8; ++j )
{
switch( board_[ i ][ j ].piece_ )
{
case Piece::None:
std::cout << " ";
break;
case Piece::Pawn:
std::cout << "P";
break;
// ...
}
}
std::cout << std::endl;
}
}
I hope this helps.

Related

Sort an array A using Quick Sort. Using reccursion

#include<iostream>
using namespace std;
void quickSort(int input[], int start, int end)
{
// your code goes here
}
void quickSort(int input[], int size)
{
quickSort(input, 0, size - 1);
}
*/
void swap(int* a,int* b){
int temp=*a;
*a=*b;
*b=temp;
}
int count(int input[],int start,int end ){
static int c=0;
if(start==end)
return c;
if(input[start]>input[end])
c++;
return count(input,start,end-1);
}
int partionArray(int input[],int start,int end ){
int c=count(input,start,end);
int pi=c+start;
swap(&input[start],&input[pi]);
int i=start;
int j=end;
while(i<pi&&j>pi)
{
if(input[i]<input[pi])
{
i++;
}
else if(input[j]>=input[pi])
{
j--;
}
else
{
swap(&input[i],&input[j]);
i++;
j--;
}
}
return pi;
}
void qs(int input[],int start, int end){
if(start>=end)
return;
int pi=partionArray(input,start,end);
qs(input,start,pi-1);
qs(input,pi+1,end);
}
void quickSort(int input[], int size) {
qs(input,0,size-1);
}
int main(){
int n;
cin >> n;
int *input = new int[n];
for(int i = 0; i < n; i++) {
cin >> input[i];
}
quickSort(input, n);
for(int i = 0; i < n; i++) {
cout << input[i] << " ";
}
delete [] input;
}
Sort an array A using Quick Sort. Using reccursion is the question.
Input format :
Line 1 : Integer n i.e. Array size
Line 2 : Array elements (separated by space)
Output format :
Array elements in increasing order (separated by space)
Constraints :
1 <= n <= 10^3
What did i do wrong in this code pls can any one explain?Is every thing right with this code?

C++ Fix the following code so that it will correctly recursively traverse a directory tree in order to find where a particular file is

I have an assignment as following: Write a program will ask the user how many random numbers to generate. Then it will present a menu which has the options of Display, Average, Median, and Standard Deviation, Regenerate, and Quit. Without the use of a switch statement, or an if statements, or pointers to functions, have the program execute the user's selection from the menu. (Note: Function pointers are not allowed!)
This is what I have so far:
#include <iostream>
#include <cstdlib>
#include <array>
#include <cmath>
#include <stdlib.h>
#include <map>
using namespace std;
template <typename T> class wrapperclass
{
public:
static T myclass;
};
class Display
{
public:
static void myFunction(int random[], int num)
{
for(int i=0; i<num; ++i)
{
cout << random[i] <<endl;
}
}
};
class Average
{
public:
static double myFunction(int random[], int num)
{
double avg = 0;
for(int i=0; i<num; ++i)
{
avg += random[i];
}
return avg/num;
}
};
class Median
{
public:
static double myFunction(int random[], int num)
{
double mid = 0;
if(num % 2 == 0)
{
mid = (random[num/2] + random[num/2-1])/2;
}
else
{
mid = random[num/2];
}
return mid;
}
};
class StdDi
{
public:
static double myFunction(int random[], int num)
{
double avg=0;
double total=0;
for(int i=0; i<num; ++i)
{
avg += random[i];
}
avg = avg/num;
for(int i=0; i<num; ++i)
{
total += (avg-random[i])*(avg-random[i]);
}
total = total/num;
return sqrt(total);
}
};
class renerate
{
public:
static void myFunction(int)
{
}
};
class quit
{
public:
static void myFunction()
{
exit(EXIT_FAILURE);
}
};
int main()
{
int num = 0;
int option = 0;
map<int, class T> magic;
cout << "How many random numbers would u like to generate? " << endl;
cin >> num;
int random[num];
for(int i=0; i<num; ++i)
{
random[i] = rand() % 100 + 1;
}
cout << " Menu"<<endl
<< "1. Display"<<endl
<< "2. Average"<<endl
<< "3. Median"<<endl
<< "4. Standard Deviation"<<endl
<< "5. Renerate"<<endl
<< "6. Quit"<<endl;
cin >> option;
cout<<wrapperclass<Average>::myclass.myFunction(random, num);
return 0;
}
I'm about to directly pass the user input "option" into that "wrapperclass" like this "wrapperclass" so I can simply call the .myFunction since all classes have the same function name. but this won't work for c++ so is there any work around?

Maximum value of range of values in array (C++)

The array ampVal has 25600 integers inside it. I need to find the maximum value of each set of 1024 values in the array and store it in another array. However I'm not getting this part to work it only gives 21 values and a random number '1348410436'. ampVal is a dynamic array.
#include<iostream>
#include<fstream>
#include<string>
#include<sstream>
using namespace std;
int main() {
ifstream miniProject;
int n = 0;
miniProject.open("C:\\Users\\Simeon Ramjit\\Desktop\\audioframes.txt");
if (!miniProject) {
cout << "File not found" << endl;
}
else {
cout<<"File Located ! :D \nCounting Lines in file..." << endl;
while (miniProject) {
string lines;
getline(miniProject, lines);
n++;
}
cout << "Number of lines in file are: " << n << endl;
miniProject.close();
}
int *frNum = new int[n];
int *bitNum = new int[n];
int *ampVal = new int[n];
for (int i = 0; i < n;i++){
frNum[i] = 0;
bitNum[i] = 0;
ampVal[i] = 0;
}
miniProject.open("C:\\Users\\Simeon Ramjit\\Desktop\\audioframes.txt");
if (!miniProject) {
cout << "File not found" << endl;
}
else {
int i = 0;
string frameNumber, bitNumber, amplitudeValue;
while (miniProject) {
(miniProject >> frameNumber >> bitNumber >> amplitudeValue);
stringstream(frameNumber) >> frNum[i];
stringstream(bitNumber) >> bitNum[i];
stringstream(amplitudeValue) >> ampVal[i];
i++;
}
}
miniProject.close();
int frameGroupStart = 0;
int frameGroupEnd = 1024;
int maxAmpVal = 0;
while (frameGroupEnd != 25600) {
for (int i = frameGroupStart; i < frameGroupEnd; i++) {
if (ampVal[i] >maxAmpVal) {
maxAmpVal = ampVal[i];
cout << maxAmpVal << endl;
}
}
frameGroupStart = frameGroupStart + 1024;
frameGroupEnd = frameGroupEnd + 1024;
}
getchar();
return 0;
}
I used an alternate approach and this gets the job done:
int bitGroupStart = 0;
int bitGroupEnd = 1024;
int arrayOfMaxAmpVal[25];
int frameNumMaxVal[25];
int maxAmpVal = 0;
for (int i = 0; i < 25; i++) {
for (int j = bitGroupStart; j < bitGroupEnd; j++) {
if (ampVal[j] > maxAmpVal) {
maxAmpVal = ampVal[j];
}
}
bitGroupStart = bitGroupStart + 1024;
bitGroupEnd = bitGroupEnd + 1024;
arrayOfMaxAmpVal[i] = maxAmpVal;
frameNumMaxVal[i] = i;
maxAmpVal = 0;
}

how to print to screen a vector?

I'm implementing the show Deal Or No Deal, there's a class 'box' which in the main file i used to store the random values of the boxes and than, i saved each box in the vector. im trying now to print in the screen the boxes saved in the vector whit the iterator,without succeeding, any help???
//random assignation of pound value to the 22 boxes
for (int e = 1; e < 23; e++)
{
int pos;
bool op = true;
while (op)
{
pos = rand();
if (pos > 0 && pos < 23)
{
if (myArray[pos][1] == 0)
{
myArray[pos][1] = 1;
op = false;
}
}
}
box b(e, myArray[pos][0]); //creating the class box
game_box.push_back(b); //function of the vector to insert a data in it
}
//show boxes
for (auto a = game_box.begin(); a!= game_box.end(); a++)
{
cout << *a << endl;
}
You first need to remove the dereference operator (*) from the a.
Next you need to add an output operator for box. Assuming that box is a class with member data member1 and member2 this would look something like:
friend std::ostream& operator<< (std::ostream &out, const box& b)
{
out << box.memeber1 << " " << box.member2;
}
The key point is that you need to define this operator for every class.
Once you've done that and got it working you might also like to look at this library which defines << operators for all stl containers. This lets you replace
for (auto a = game_box.begin(); a!= game_box.end(); a++)
{
cout << *a << endl;
}
by simply
cout << game_box << endl;
this works..
class Box
{
float pound_contained;
int box_number;
public:
Box(int box_number, float pound_contained);
int getbox_number();
float getpound_contained();
};
int Box::getbox_number()
{
return this->box_number;
}
float Box::getpound_contained()
{
return this->pound_contained;
}
main()
{
vector<Box> game_box;
Box* boxes = &game_box[i];
cout <<boxes->getbox_number()<<endl;
}

Creating a Linked list with Structs - C++

I was writing a program which could read an input file and store the read data in nodes linked by a "link list". However, I was getting a few errors:
In constructor List::List(), no match for 'operator =' in *((List*)this)->List::list[0] = 0
In constructor Polynomial::Polynomial(): no match for 'operator =' in *((Polynomial*)this)->Polynomial::poly = (operator new(400u), (<statement>), ...)
I have a feeling where I do: I try to access a certain node through an array is where I go wrong, however, I can't figure it out much.
Here is the code:
#include <iostream>
#include <fstream>
using namespace std;
enum result{success, failure};
struct Node
{
double coefficient;
int power;
Node();
Node(double coef, int pwr);
};
struct List
{
Node *list[100];
//Default constructor
List();
};
Node::Node()
{
coefficient = 0;
power = 0;
}
List::List()
{
*list[0] = NULL;
}
Node::Node(double coef, int pwr)
{
coefficient = coef;
power = pwr;
}
class Polynomial
{
public:
Polynomial();
result multiply(Polynomial &p, Polynomial &q);
result add(Polynomial p, Polynomial &q);
void initialize(ifstream &file);
void simplify(Polynomial &var);
void print_poly();
~Polynomial();
private:
List *poly; //Store the pointer links in an array
Node first_node;
int val;
};
Polynomial::Polynomial()
{
*poly = new List();
}
Polynomial::void initialize(ifstream &file)
{
int y[20];
double x[20];
int i = 0, j = 0;
//Read from the file
file >> x[j];
file >> y[j];
first_node(x[j], y[j++]); //Create the first node with coef, and pwr
*poly->list[i] = &first_node; //Link to the fist node
//Creat a linked list
while(y[j] != 0)
{
file >> x[j];
file >> y[j];
*poly->list[++i] = new Node(x[j], y[j++]);
}
val = i+1; //Keeps track of the number of nodes
}
Polynomail::result multiply(Polynomial &p, Polynomial &q)
{
int i, j, k = 0;
for(i = 0; i < p.val; i++)
{
for(j = 0; j < q.val; j++)
{
*poly->list[k] = new Node(0, 0);
*poly->list[k].coefficient = (p.poly->list[i].coefficient)*(q.poly->list[j].coefficient);
*poly->list[k++].power = (p.poly->list[i].power)+(q.poly->list[j].power);
}
}
val = k+1; //Store the nunber of nodes
return success;
}
Polynomial::void simplify(Polynomial &var)
{
int i, j, k = 0;
//Create a copy of the polynomial
for(j = 0; j < var.val; j++)
{
*poly->list[j] = new Node(0, 0);
*poly->list[j].coefficient = var.poly->list[j].coefficient;
*poly->list[j].power = var.poly->list[j].power;
}
//Iterate through the nodes to find entries which have the same power and add them, otherwise do nothing
for(k = 0; k < var.val; k++)
{
for(i = k; i < var.val;)
{
if(*poly->list[k].power == var.poly->list[++i].power)
{
if(*poly->list.power[0] == 0)
{
NULL;
}
else
{
*poly->list[k].coefficient = *poly->list[k].coefficient + var.poly->list[i].ceofficient;
var.poly->list[i] = Node(0, 0);
}
}
}
}
}
Polynomial::void print_pol()
{
int i = 0;
for(i = 0; i < temp.val; i++)
{
cout << "Coefficient: " << temp.poly->list[i].coefficient << ", and " << "Power: " << temp.poly->list[i].power << endl;
}
}
The problem is a wrong dereference. Line 34 should probably be
list[0] = NULL; // remove the *
You try to assign the value NULL to a variable of the type Node, but you probably mean a pointer to Node.
The very same is true in line 63.
In addition, line 66 sould probably b:
void Polynomial::initialize(ifstream &file) // start with return type