I have class A and method call a_method, I have class B with and object b_object, and I wanted to pass object b_object as an argument into a_method, but how do I declare it in a_method?
#include <iostream>
#include <vector>
class Board{
int sizeofboard;
std::vector<std::vector<int>> board;
public:
Board(int sizeofboard){
this->sizeofboard = sizeofboard;
int n = 1;
for (int i = 0; i < sizeofboard; i++){
board.push_back(std::vector<int>());
for (int j = 0; j < sizeofboard; j++){
board[i].push_back(n);
n++;
}
}
}
display(){
for (int i = sizeofboard-1; i >= 0; i--){
std::cout << " ";
for (int j = 0; j < sizeofboard; j++){
if (j == sizeofboard-1){
std::cout << board[i][j];
continue;
}
std::cout << board[i][j] << " | ";
}
std::cout << std::endl;
if (i == 0)continue;
std::cout << "---+---+---" << std::endl;
}
}
draw(int position, Player &player){
int i, j;
int i = position/3;
if (i == 0)i = 2;
j = position%3;
}
};
class Player{
char symbol;
public:
};
int main()
{
Board board(3);
Player player1;
board.display();
return 0;
}
so the part of draw I am confused on how to declare it. it says Player has not been declared
draw(int position, Player &player){
A C++ compiler compiles a C++ program from beginning to the end. At this point, your C++ compiler does not know anything about this mysterious class called Player, which has not been declared yet.
You can simply move the definition of Player before this class. In other cases a forward declaration is all that's needed.
In situations involving complex dependencies between classes it might be necessary to merely declare all classes, first, then defer the definition of all class members until everything is fully defined.
In this case moving the declaration first will solve this particular error (but not other, unrelated compilation errors). This may change, depending on any code that's not shown here.
The below working example shows what you want:
#include <iostream>
#include <vector>
class Player{
public:
char symbol = 'A';
};
class Board{
int sizeofboard;
std::vector<std::vector<int>> board;
public:
Board(int sizeofboard){
this->sizeofboard = sizeofboard;
int n = 1;
for (int i = 0; i < sizeofboard; i++){
board.push_back(std::vector<int>());
for (int j = 0; j < sizeofboard; j++){
board[i].push_back(n);
n++;
}
}
}
//this display function takes Player be reference
void display(Player &player){
for (int i = sizeofboard-1; i >= 0; i--){
std::cout << " ";
for (int j = 0; j < sizeofboard; j++){
if (j == sizeofboard-1){
std::cout << board[i][j];
continue;
}
std::cout << board[i][j] << " | ";
}
std::cout << std::endl;
if (i == 0)continue;
std::cout << "---+---+---" << std::endl;
}
std::cout<<player.symbol<<std::endl;//this prints the player1 symbol value
}
void draw(int position, Player &player){
int j;
int i = position/3;
if (i == 0)i = 2;
j = position%3;
}
};
int main()
{
Board board(3);
Player player1;
board.display(player1);//pass player1 object by reference.
return 0;
}
Note that from inside the display() method we have printed out the symbol data member's value.
Related
so I am having a little bit of trouble getting this program to work without it throwing the errors:
"request for member 'insertArray' in 'arr', which is of non-class type 'int [10]' " and
"request for member 'print' in 'arr', which is of non-class type 'int [10]' ".
Both of those errors have to do with using my functions with an array, you can see the code below:
#include <iostream>
using namespace std;
int size = 0;
int *arr;
void insertArray(int val)
{
int i = 0;
while (i < size && arr[i] < val)
i++;
for (int k = size - 1; k >= i; k--)
{
arr[k + 1] = arr[k];
}
arr[i] = val;
size++;
}
void print()
{
cout << "The array is: ";
for (int j = 0; j < size; j++)
{
cout << arr[j];
}
}
int main()
{
int arr[10];
cout << "Please enter 5 values: \n";
for (int i = 0; i < 5; i++)
{
int num = 0;
cin >> num;
arr.insertArray(num); // Error 1: vs code error squiggles say: "expression must have class type"
arr.print(); // Error 2: vs code error squiggles say: "expression must have class type"
}
return 0;
}
I don't know how to fix the errors or what they mean either.
Thanks for the help in advance folks!
arr is just a plain-old C array, you can't define new functions on it. You need to define a class or struct if you want to do that.
What you have here is procedural code, so you're constrained by that model and must pass in arr as an argument.
I've tried to wrangle your original code into this form with as few modifications as necessary:
#include <iostream>
void printArr(const int* arr, const size_t size)
{
std::cout << "The array is: ";
for (int j = 0; j < size; j++) {
std::cout << arr[j];
}
std::cout << std::endl;
}
int main()
{
const size_t count = 5;
int arr[count];
std::cout << "Please enter 5 values: \n";
for (int i = 0; i < 5; i++)
{
std::cin >> arr[i];
}
printArr(arr, count);
return 0;
}
The whole insertArray function was just too confusing so I deleted it presuming what you were trying to do was add things at the end of the array anyway.
I was assigned to make a game of hearts where there is an array of 4 people and each people has a hand of 13 cards. Currently, when dealing trying to deal cards to each person deck, I am only able to accomplish this using pointers. However, this has posed problems in getting other functions like sort and such to work. I know that it's possible to do it without pointers I'm just not sure how and was wondering if anybody could assist.
In the psudocode, my teacher gave us, the hand[13] array which holds the cards is not a pointer, but I made it a pointer in order to points the cards to it.
#include <iostream>
#include <iomanip>
#include "Card.h"
#include "Player.h"
#include <cstdlib>
#include <random>
using namespace std;
//Prototype
void shuffleDeck(Card deck1[])
{
int ranNum;
Card temp;
int count = 0;
for(int i = 0; i < 52; i++)
{
count++;
ranNum = (rand() % 52);
temp = deck1[ranNum];
deck1[ranNum] = deck1[i];
deck1[i] = temp;
}
}
int main()
{
//Declarations
int nextPlayer;
int firstPlayer;
Card deck2[4][13];
Suit temp;
Card deck1[52];
int count = 0;
int check = 0;
int round = 0;
int points = 0;
int numCards = 0;
//Part 1: The set-up
//Create player array of [4] players
Player player[4] = {Player("Me"),
Player("Elton John"),
Player("Snoop Dog"),
Player("Lady Gaga")
};
//create and initialize deck;
for (int r = 0; r < 4; r++)
{
for (int c = 0; c < 13; c++)
{
deck2[r][c].setNumber(c + 1);
temp = ((Suit)r);
deck2[r][c].setSuit(temp);
deck2[r][c].setDescription();
}
}
//Convert to one dimensional array
for(int i = 0; i < 4; i++)
{
for(int j = 0; j < 13; j++)
{
deck1[count] = deck2[i][j];
count++;
}
}
shuffleDeck(deck1); //call shuffle deck function
//Deal deck to players // have add card in player class that sticks a card in players deck
/*
for(int i = 0; i < 52; i++)
{
int playerIndex = i % 4;
player[playerIndex].addCard(&deck1[i]); //HERE IS WHERE I CALL IT IN THE MAIN
}
//Sort each players hand
for (int i = 0; i < 4; i++)
{
player[i].sort();
}
//Find player who goes first (the person holding the 2 of clubs) //firstPlayer
for(int j = 0; j < 4; j ++)
{
for(int i = 0; i < 13; i++)
{
if(player[j].getCard(i) == 20)
{
firstPlayer = j;
}
}
}
*/
Card openCard[4]; //keeps track of all played cards
// //Part 2: The play
for(int i = 0 ; i < 13; i++) //gonna play 13 rounds, same thing 13 times
{ numCards = 0;
round++;
// Print points of players
cout << "\nPlayer Round " << round << " Total\n";
cout << "------- -------- -----\n";
cout << "\nMe ";
cout << "\nSnoop Dogg ";
cout << "\nLady Gaga ";
cout << "\nElton John ";
// Print hand
cout << "\n\nMy Hand: \n" << "-------------\n\n";
for(int i = 0; i < 13; i++)
{
// cout << player[0].getCard(i) << "\n";
numCards++;
check++;
cout << numCards << ".) " << deck1[i].getDescription() << "\n";
}
for (int j = 0; j < 3; j++)
{
nextPlayer = (firstPlayer + j) % 4;
//Play a card
//Compare card to other card
// openCard[nextPlayer] = player[nextPlayer].playCard(deck1[i], firstPlayer);
//inside playCard() remove card from hand after it's played
// hand[cardPlayed] = null //null means played already// (I think this is another method of doing it)
}
//end for j
//count points per player
//firstPlayer = winner of round //implement this in
// if(firstPlayer) //something like this
// {
// points++;
// }
//add points to first player
}
//end for i
return 0;
}
//PLAYER CLASS
#ifndef PLAYER_H
#define PLAYER_H
#include "Card.h"
#include <iostream>
#include <iomanip>
using namespace std;
class Player
{
//Member variables
private:
string name;
public:
static int count;
Card *hand[13]; //TRYING TO MAKE THIS NOT A POINTER
int number;
bool played;
//Constructors
Player()
{
name = "";
}
Player(string n)
{
name = n;
}
string getName()
{
return name;
}
int getCard(int index)
{
return hand[index]->getNumber();
}
void setName(string n)
{
name = n;
}
// void addCard(Card *card) //THIS IS WHERE CARDS ARE DELT (HOW DO I
MAKE IT NOT A POINTER?)
// {
// if (number < 13)
// {
// hand[number] = card;
// number++;
// }
// }
// void sort()
// {
// for (int i = 1; i < 13; i++)
// {
// Card *temp;
// bool swap = false;
// int size = 52;
// do
// {
// swap = false;
// for (int count = 0; count < (size - 1); count++)
// {
// if (hand[count + 1] < hand[count])
// {
// temp = hand[count];
// hand[count] = hand[count + 1];
// hand[count + 1] = temp;
// swap = true;
// }
// }
// }
// while (swap == true);
// }
// }
// Card playCard(Suit lead, bool leader)
// {
// int cardPlayed;
// hand[cardPlayed] = -1; //null means played already// (I think this
is another method of doing it)
// }
};
#endif
I have a constructor and a method in an implementation file:
Boggle::Boggle(std::string boardString){
dim = sqrt(boardString.size());
vector<vector<char> > grid(dim, vector<char>(dim));
int co = 0;
for (int i = 0; i < dim; i++)
{
for (int j = 0; j < dim; j++)
{
grid[i][j] = boardString[co];
co++;
}
}
}
void Boggle::printMe() {
for (auto inner : grid)
{
for (auto item : inner)
{
cout << item << " ";
}
cout << endl;
}
}
The program executes, but doesn't do anything. As you can see I have sized my vector when I declared it. I believe the issue lies in my logic of assigning a character to a vector from a string perhaps.
As hinted in comments your vector grid is local to your function. You mostly likely wanted to use a class variable but ended up creating a local variable. You can use resize to set the dimensions of your grid. Also its better to ceil the sqrt to make sure that we are not missing any characters.
Example:
#include <stdio.h>
#include <vector>
#include <string>
#include <cmath>
#include <iostream>
using namespace std; // Avoid this
class Boggle{
public:
int dim;
vector<vector<char>> grid;
Boggle(string boardString);
void printMe();
};
Boggle::Boggle (std::string boardString)
{
dim = ceil(sqrt(boardString.size ()));
grid.resize(dim, vector <char>(dim));
int co = 0;
for (int i = 0; i < dim; i++) {
for (int j = 0; j < dim; j++)
{
grid[i][j] = boardString[co];
co++;
}
}
}
void Boggle::printMe ()
{
for (auto inner:grid) {
for (auto item:inner)
{
cout << item << " ";
}
cout << endl;
}
}
int main(){
Boggle boggle("hello world");
boggle.printMe();
return 0;
}
Result:
h e l l
o w o
r l d
This project I am writing in order to create a Square Matrix ADT object has a problem with the constructor (not the default constructor). I have traced the problem back to the constructor but I cannot figure out what is wrong with it which makes it crash everytime I try to run my test in main.cpp.
I usually get an error that say something along the lines "Thread 1: EXC_BAD_ACCESS: ..." and the console usually says "(11db)"
Does anyone have any ideas on what might be causing all the problems?
This is the header file:
#include <iostream>
#include <vector>
using namespace std;
#ifndef SquareMatrix_h
#define SquareMatrix_h
class SquareMatrix {
private:
vector<vector<double>> numMatrix;
public:
SquareMatrix();
SquareMatrix(vector<vector<double>>& v2d);
double getValue(int x, int y);
void setValue(int x, int y, double value);
friend SquareMatrix operator * (SquareMatrix m1, SquareMatrix m2);
friend SquareMatrix operator - (SquareMatrix m1, SquareMatrix m2);
friend ostream& operator <<(ostream &out, SquareMatrix m);
};
#endif /* SquareMatrix_h */
This is my SquareMatrix.cpp file: (The constructor that I believe isn't working is the second function in the code: SquareMatrix::SquareMatrix(vector>& v2d) {...)
#include "SquareMatrix.h"
#include <iostream>
using namespace std;
SquareMatrix::SquareMatrix() {
numMatrix.clear();
for(int i = 0; i < 10; i++) {
vector<double> initial;
for(int j = 0; j < 10; j++) {
initial.push_back(0.0);
}
numMatrix.push_back(initial);
}
}
SquareMatrix::SquareMatrix(vector<vector<double>>& v2d) {
bool flagSize = true;
for(int i = 0; i < v2d.size(); i++) {
if(v2d[i].size() != v2d.size()) {
flagSize = false;
break;
}
}
if(flagSize) {
numMatrix.clear();
for(int i = 0; i < v2d.size(); i++) {
vector<double> initial;
for(int j = 0; j < v2d[i].size(); i++) {
initial.push_back(v2d[i][j]);
}
numMatrix.push_back(initial);
}
} else {
numMatrix.clear();
for(int i = 0; i < 10; i++) {
vector<double> initial;
for(int j = 0; j < 10; j++) {
initial.push_back(0.0);
}
numMatrix.push_back(initial);
}
}
}
double SquareMatrix::getValue(int x, int y) {
if((x < numMatrix.size()) && (y < numMatrix.size()) && (x >= 0) && (y >= 0)) {
return numMatrix[x][y];
}
return 0;
}
void SquareMatrix::setValue(int x, int y, double value) {
if((x < numMatrix.size()) && (y < numMatrix.size()) && (x >= 0) && (y >= 0)) {
numMatrix[x][y] = value;
}
}
SquareMatrix operator * (SquareMatrix m1, SquareMatrix m2) {
if(m1.numMatrix.size() == m2.numMatrix.size()) {
vector<vector<double>> result;
for(int i = 0; i < m1.numMatrix.size(); i++) {
vector<double> initial;
for(int j = 0; j < m1.numMatrix.size(); j++) {
initial.push_back(0);
}
result.push_back(initial);
}
for(int i = 0; i < m1.numMatrix.size(); i++) {
for(int j = 0; j < m1.numMatrix.size(); j++) {
result[i][j] = 0;
for (int a = 0; a < m1.numMatrix.size(); a++) {
result[i][j] += m1.numMatrix[i][a] + m2.numMatrix[a][j];
}
}
}
return SquareMatrix(result);
}
return SquareMatrix();
}
SquareMatrix operator - (SquareMatrix m1, SquareMatrix m2) {
if(m1.numMatrix.size() == m2.numMatrix.size()) {
vector<vector<double>> result;
for(int i = 0; i < m1.numMatrix.size(); i++) {
vector<double> initial;
for(int j = 0; j < m1.numMatrix[i].size(); j++) {
double pushNum = (m1.getValue(i,j) - m2.getValue(i,j));
initial.push_back(pushNum);
}
result.push_back(initial);
}
return SquareMatrix(result);
}
return SquareMatrix();
}
ostream& operator << (ostream &out, SquareMatrix m) {
out << "(";
for (int i = 0; i < m.numMatrix.size(); i++) {
for (int j = 0; j < m.numMatrix.size(); j++) {
out << " " << m.numMatrix[i][j];
if(j != (m.numMatrix.size() - 1)) {
out << ", ";
}
}
}
out << ")";
return out;
}
Then this is the main.cpp that I am using to test the SquareMatrix ADT object:
#include "SquareMatrix.h"
#include <iostream>
#include <random>
#include <ctime>
#include <vector>
using namespace std;
int main() {
srand(time(NULL));
vector<vector<double>> m1;
vector<vector<double>> m2;
int size = 0;
cout << "Enter the size of the Square Matrix: ";
cin >> size;
for (int i = 0; i < size; i++) {
vector<double> in1;
vector<double> in2;
for (int j = 0; j < size; j++) {
in1.push_back(rand() % 100);
in2.push_back(rand() % 100);
}
m1.push_back(in1);
m2.push_back(in2);
}
SquareMatrix res1 = SquareMatrix(m1);
SquareMatrix res2 = SquareMatrix(m2);
cout<< "\nMatrix 1: " << endl;
cout << res1 << endl;
cout<< "\nMatrix 2: " << endl;
cout << res2 << endl;
SquareMatrix mult = res1*res2;
cout << "\nMatrix1 * Matrix 2: " << endl;
cout << mult << endl;
SquareMatrix min1_2 = res1 - res2;
cout << "Matrix1 - Matrix 2: " << endl;
cout << min1_2 << endl;
SquareMatrix min2_1 = res2 - res1;
cout << "Matrix2 - Matrix 1: " << endl;
cout << min2_1 << endl;
return 0;
}
Any help you could give would be appreciated. :)
As pointed out in the comments, you problem is a simple typo in one of your nested loops. However, I'd like to add some recommendations to make your code less error prone (and also more readable).
Firstly, when iterating over all elements of a vector, unless you need an index for something else, you should be using a range-based for-loop. In your code, you might replace the check for square size with the following:
for (const vector<double>& vec: v2d){
if (vec.size() != v2d.size()){
flagSize = false;
break;
}
}
This expresses your intent a little more clearly, and, more importantly, prevents you from accidentally reading from/writing to a location out of your vector's bounds (accidentally typing <= instead of just < happens to the best of us).
Secondly, the two nested loops (that contained your error) can be replaced with a simple copy assignment (numMatrix = v2d; reference). Again, this expresses your intent in addition to being a whole lot shorter. No need to reinvent the wheel with functions like these.
The contents of the else-branch of the surrounding if-statement can also be replaced with a call to assign (the first overload listed on the page, use like numMatrix.assign(10, vector<double>(10, 0.0))). Like before, clearer expression of intent and avoidance of index errors.
Finally, the parameter in this constructor can be a const reference instead of a normal one since you do not alter its contents in any way (and, given this, it should be const).
You might wonder why "expression of intent" is relevant, or what it even means in this context. Essentially, it's all about making what you're trying to do immediately obvious to any reader. This is more important in large projects with many contributors but it is helpful even when debugging small applications like this one. You seem to be learning still, but I strongly believe it's a good thing to keep in mind from the beginning. After all, many of these changes also make for briefer code, making it that much easier for others to help you if you run into a problem.
I realize this left the scope of the original question somewhat, but I hope you find this helpful nonetheless.
I have a class called magicSquare with a constructor and a display function called display. The constructor creates the magic square, and the display function displays the results. In my main function, I created an instance of magicSquare called ms and gave it a value 7. To display it, shouldn't it work if I just did ms.display()?
class magicSquare
{
private:
int size, square;
vector<vector <int> > finalvec;
public:
magicSquare(int a):finalvec(a, std::vector<int>(a))
{
int i = 0;
int j = a/2;
size = a;
square = a * a;
vector<int>vec(a);
vector<vector<int> > finalvec(a,vec);
for (int i = 0; i < size; i++)
{
for (int j = 0; j< size; j++)
cout << finalvec[i][j];
cout << endl;
}
for (int k=0; k < square; ++k)
{
finalvec[i][j] = k;
i--;
j++;
if (k%a == 0)
{
i = i+ 2;
--j;
}
else
{
if (j==a)
j = j- a;
else if (i<0)
i = i+ a;
}
}
}
void display()
{
for (int i = 0; i < size; i++)
{
for (int j = 0; j< size; j++)
cout << finalvec[i][j];
cout << endl;
}
}
};
int main()
{
magicSquare ms(3);
ms.display();
return 0;
}
Your Error
As pointed by #Retired Ninja, the vector > finalvec(a,vec); hide your member variable finalvec, as you redefine it as a new vector...
What can correct it
You could construct your vector inside a Member initializer list like this
magicSquare(int a) : finalvec(a, std::vector<int>(a, 0)) {
/* your constructor */
}
And delete the two line:
vector<int>vec(a);
vector<vector<int> > finalvec(a,vec);
In your code
How to not make this error
Seeing which value are a class member, method parameter or even context variable can be sometime difficult:
What i can recommend you is to do the following:
class member -> m_NAME_OF_YOUR_CLASS_MEMBER
method parameter -> t_NAME_OF_YOUR_METHODE_PARAMETER
context variable -> c_NAME_OF_YOUR_CONTEXT_VARIABLE
by doing this error like you've done is a bit harder to do!
EDIT: After testing your code
I see there's error in it, effectively, the first time you go in that line:
finalvec[i][j] = k;
i > size, so you access further that your vector allow it, which result in a segfault! please repair your code!
hope that can help