Loop through an array - c++

I would like to know, how to loop through a array of int to get its value and set its value. I know how to use the for loop to to get instantly, but I am not sure how it works, when I am using in user created objects and esp using the get set method.
I am totally new to this and have very little guidance from my lectures. I hope you guys can assist to help me. This up to where I have done.
//point.h
class point {
private:
int x[4];
public:
int getx();
void setx();
};
//point.cpp
class point {
point::getx(){
// ??????
}
point::setx(){
// ???????
}
//main.cpp
int main(){
point objPoint;
objPoint.setx(/* ???? */);
???? = objPoint.getx();
}

First of all, your getx method should return int*, not just int, and your setx should receive const int* as parameter. Second, in your point.cpp file you shouldn't redeclare class point.
int* point::getx() { //version with copying
int* ans = new int[4];
for (int i = 0; i < 4; i++) {
ans[i] = x[i];
}
return ans;
}
void point::setx(const int* y) {
for (int i = 0; i < 4; i++) {
x[i] = y[i];
}
}
Then you can use them like this
int y[4] = {1, 2, 3, 4};
int* z;
objPoint.setx(y);
z = objPoint.getx();
Just don't forget to delete[] z when you're done.

If I'm understanding you correctly, you probably want something like more this:
point.h:
class Point{
private:
int x, y;
public:
int getx();
int gety();
void setx(int value);
void sety(int value);
};
point.cpp
int Point::getx() { return x; }
int Point::gety() { return y; }
void Point::setx(int value) { x = value; }
void Point::sety(int value) { x = value; }
main.cpp
int main(int argc, char *argv[])
{
Point objPoint;
objPoint.setx(1);
int x = objPoint.getx();
cout << "x=" << x << endl;
return 0
}
Even better, you might wish to define a constructor like Point (int xvalue, int yvalue).
IMHO ...

Related

how do i initialize a public variable in a public class method

I have a public class in which I create an array, this array takes its size from the constructor and needs to be used in other functions (including int main). Therefore the variable must be public. my code looks something along these lines:
class myclass {
public:
int parameter1;
int parameter2;
myclass(int p, int p2) {
parameter1 = p;
parameter2 = p2;
}
void makeArray() {
int array[parameter1][parameter2]; //I want this array to be public as the next method needs access to it
}
void otherFunction() {
array[1][2] = 5; //just an example of what i need to do
}
}
Look up how to use pointers and dynamic memory..
To do what you want would be something like:
class myclass {
public:
int parameter1;
int parameter2;
int **a;
myclass(int p, int p2) {
parameter1 = p;
parameter2 = p2;
a = nullptr;
}
~myclass() {
// TODO: delete "a"
}
void makeArray() {
// TODO: delete "a" if it has already been allocated
a = new *int[parameter1];
for (int i = 0; i < parameter1; ++i) {
a[i] = new int[parameter2];
}
}
void otherFunction() {
// TODO: check that "a" has already been allocated
a[1][2] = 5; //just an example of what i need to do
}
}
You could also allocate the array in the constructor since you have the necessary information being passed in already.
This is more optimized way to do the same thing:
class myclass {
public:
int parameter1;
int parameter2;
int *array;
myclass(int p1, int p2) {
parameter1 = p1;
parameter2 = p2;
}
void makeArray() {
array = new int[parameter1*parameter2];
}
void otherFunction() {
// ary[i][j] is then rewritten as ary[i*sizeY+j]
array[1*parameter2+2] = 5;
}
};
int main()
{
int sizeX = 5;
int sizeY = 5;
myclass m1(sizeX,sizeY);
m1.makeArray();
m1.otherFunction();
cout << m1.array[1*sizeY+2] << endl;
return 0;
}

Accessing double pointer from another class

I'd like to access to a double pointer which is located in another class "Board".
class Board
{
public:
Board(void);
Board(unsigned int xSize, unsigned int ySize);
~Board(void);
void SetObjectManager(ObjectManager* pObm);
void SetBlock(Block* block);
void LoadBoard(void);
void InitBoard(void);
//Other Functions...
private:
ObjectManager* m_obm;
Block* m_block;
//pointer to pointer to a int. (for 2 dimensional-array)
int **m_board;
};
First, the Board class. at the last line of class, you can see m_board.
I want to change this value in outside of this class.
Like this,
void Block::InitBlock(void)
{
int randPiece = Random::GIRand().RandInt(0, 1);
int randPos = Random::GIRand().RandInt(0, 10);
switch (randPiece)
{
case 0:
m_piece[2][1] = 1;
m_piece[2][2] = 1;
m_piece[2][3] = 1;
m_piece[3][3] = 1;
break;
//Other cases are here...
}
std::cout << "RandPos : " << randPos << std::endl;
std::cout << "RandPiece : " << randPiece << std::endl;
for (int y = 0; y < m_ySize; ++y)
{
for (int x = 0, pX = randPos; x < m_xSize; ++x, ++randPos)
{
if (m_piece[x][y] != 0)
m_board->SetBoardStatus(randPos, y, 1);
}
}
}
But, When I run this program, It blows up at SetBoardStatus(int, int, int)
SetBoardStatus looks like this,
void Board::SetBoardStatus(int x, int y, int value)
{
m_board[x][y] = value; //Visual Studio breaks the program here.
}
I allocate the double pointer properly.
And I set the board at the outside of this classes.
void Block::SetBoard(Board* board)
{
m_board = board;
}
And this is my block class.
class Block
{
public:
Block(void);
~Block(void);
void SetObjectManager(ObjectManager* pObm);
void LoadBlock (void);
void InitBlock (void);
void UpdateBlock (void);
void ReleaseBlock (void);
void SetBoard(Board* board);
private:
ObjectManager* m_obm;
Board* m_board;
int **m_piece;
int m_xSize;
int m_ySize;
};
Consider inheriting Block in Board; This will eliminate any possible de-referencing errors or bugs, as you can access the pointer right away.

Creating 2D-Array inside a constuctor in C++

I am trying to do the following:
class Test{
private:
int x;
int y;
// Create array[][] here
public:
Test(const int x, const int y){
this->x = x;
this->y = y;
// set: array[x][y] here
}
};
As you see I would like to create a 2d-Array, while the bounds will be given in the constructor.
How can I achieve this?
It works with an usual array:
class Test{
private:
int x;
int y;
int *array;
public:
Test(const int x, const int y){
this->array = new int[x]; // works
// this->array = new int[x][y] does not work
this->x = x;
this->y = y;
}
};
You may be bumping into the problem of "All dimensions must be constants except the leftmost" discussed here.
Instead, try the following:
class Test {
private:
int x;
int y;
int** myArray;
public:
Test(const int x, const int y) : x(x), y(y) {
myArray = new int*[x];
for (int firstDimension = 0; firstDimension < x; firstDimension++) {
myArray[firstDimension] = new int[y];
for (int secondDimension = 0; secondDimension < y; secondDimension++) {
myArray[firstDimension][secondDimension] = secondDimension;
}
}
}
~Test() {
for(int i = 0; i < x; i++)
delete[] myArray[i];
delete[] myArray;
}
};
you should consider allocating memory with pointers, should be as follows:
class Test{
private:
int x;
int y;
int **array;
public:
Test(const int x, const int y){
int i;
this->array = new int*[x]; // first level pointer asignation
for(i=0;i<x;i++){
this->array[x] = new int[y]; // second level pointer asignation
}
// this->array = new int[x][y] does not work
this->x = x;
this->y = y;
}
};
see this.

Error when resizing vector of object

I am trying to create a vector of objects but i have some issues. I can't push_back over 19 objects to my vector because it shows up an error message of bad_alloc.
I try to resize my vector with resize() or reserve() but still nothing.
For resize(), I read that you need to provide 2 arguments to resize a vector.But still nothing.
When I try to use it without push_back it shows error: expected primary-expression before ')' token.
#define N 10 //ari8mos seirwn tou xarth
#define M 10 //ari8mos sthlwn tou xarth
#define TREAS 100//posothta 8usaurou
#define PORTS 100//ari8mos limaniwn
extern void ships(map (&myArray)[N][M], vector<ship> &myShips);
void ships(map (&myArray)[N][M], vector<ship> &myShips)
{
int i,j,y;
srand ( time(NULL) );
//myShips.reserve(21);
//myShips.resize(20,ship);
cout << myShips.capacity() << endl;
int x=0;
for( i = 0; i <19 ; i++){
myShips.push_back(pirate(rand() % N,rand() % M,100,100,100,1,'#',myArray,myShips));
}
for( i=0;i<myShips.size();i++ ){
cout << myShips[i].get_symbol() << " ";
}
}
here is the rest of code to help you understand:
class ship
{
protected:
int i,j,x2,y2;
//vector<vector<map> > myArray;
//ship (&myShips)[N][M];
int x;
int y;
map (myArray)[N][M];
vector<ship> myShips;
int max_resistance;
int current_resistance;
int speed;
int reserve_treasure;
char symbol;
public:
ship(int x_, int y_, int max_res, int cur_res, int res_treas, int sp, char sy, map (&myArr)[N] [M], vector<ship> &Ship)
:x(x_)
,y(y_)
,max_resistance(max_res)
,current_resistance(cur_res)
,reserve_treasure(res_treas)
,speed(sp)
,symbol(sy)
,myArray(myArr)
,myShips(Ship)
{cout << "eimai o 'ship' 2" << endl; }
~ship() {}
int get_x();
int get_y();
float get_max_resistance();
float get_current_resistance();
int get_speed();
float get_reserve_treasure();
char get_symbol();
void set_x(int pos_x);
void set_y(int pos_y);
void set_max_resistance(float maxres);
void set_current_resistance(float curres);
void set_speed(int sp);
void set_reserve_treasure(float restrea);
void set_symbol(char sy);
void movement();
void operation();
};
int ship::get_x(){
return x;
}
int ship::get_y(){
return y;
}
float ship::get_max_resistance(){
return max_resistance;
}
float ship::get_current_resistance(){
return current_resistance;
}
int ship::get_speed(){
return speed;
}
float ship::get_reserve_treasure(){
return reserve_treasure;
}
char ship::get_symbol(){
return symbol;
}
void ship::set_x(int pos_x){
x = pos_x;
}
void ship::set_y(int pos_y){
y = pos_y;
}
void ship::set_max_resistance(float maxres){
max_resistance = maxres;
}
void ship::set_speed(int sp){
speed = sp;
}
void ship::set_current_resistance(float curres){
current_resistance = curres;
}
void ship::set_reserve_treasure(float restrea){
reserve_treasure = restrea;
}
void ship::set_symbol(char sy){
symbol = sy;
}
class pirate : public ship
{
public:
pirate(int posx, int posy, float mr, float cr, float rt, int spe, char sym, map (&Array)[N] [M],vector<ship> &Ship ):ship(posx,posy,mr,cr,rt,spe,sym,Array,Ship){
cout << "eimai o 'pirate' 1" << endl;
// ship(90,90,1,50,'#',Array,Ship) {//vector<vector<map> > Array, vector<vector<ship> > Ship) {}
};
Hope you can help
Looking through this code, did you create a custom definition for map? Otherwise, if you are trying to create an [N][M] array of Map objects, you are missing the type declaration of map. e.g. map<int,string>
If you are trying to use map as a multidimensional array, this is not what std::map is for. Map is a generic container for storing key/value pairs.

Getting Unresolved External error

I have made a class and it compiles with no syntax errors, but I get 6 unresolved external symbols?
THE CLASS:
struct CELL {
private:
static bool haslife;
static int x;
static int y;
public:
static bool has_life()
{
return haslife;
}
static void set_coords(int xcoord, int ycoord)
{
x = xcoord;
y = ycoord;
}
static void get_coords(int &xcoord, int &ycoord)
{
xcoord = x;
ycoord = y;
}
};
class cell_grid {
private:
static int cell_size;
static int cell_count_x;
static int cell_count_y;
CELL **cell;
public:
cell_grid();
cell_grid(unsigned int width,unsigned int height, unsigned int cellsize)
{
//set size based on cellsize
this->cell_size = cellsize;
this->cell_count_x = floor((double)width / this->cell_size);
this->cell_count_y = floor((double)height / this->cell_size);
this->cell = new CELL*[this->cell_count_y];
for(int i = 0; i < this->cell_count_y; i++)
{
cell[i] = new CELL[this->cell_count_x];
}
for(int y = 0; y < this->cell_count_y; ++y)
{
for(int x = 0; x < this->cell_count_x; ++x)
{
int cur_x = x * this->cell_size;
int cur_y = y * this->cell_size;
this->cell[x][y].set_coords(cur_x,cur_y);
}
}
} //end of constructor
static int get_cell_size()
{
return cell_size;
}
static void render(BITMAP *buff)
{
circlefill(buff,70,70,60,makecol(27,37,0));
}
};
MAIN
int main()
{
start_allegro();
cell_grid *grid = new cell_grid(scr_w,scr_h,10);
grid->render(buffer);
//Main Loop
while (!done && !key[KEY_ESC]) //until 'X' pressed or ESC
{
//***** Start Main Code Here *****
while (speed_counter > 0)
{
//render the buffer to the screen
blit(
buffer,
screen,
0,0,0,0,
scr_w,
scr_h);
clear_bitmap(buffer);
speed_counter --;
}
//***** End Main Code Here *****
rest(1); //Normalize cpu usage
}
return 0;
}
END_OF_MAIN()
Thanks
Don't define all of the class variables as static.
When you define a data member as static it means there is only one single instance of it. This doesn't seem to be what you want to do here.
Instead of
private:
static bool haslife;
static int x;
static int y;
write:
private:
bool haslife;
int x;
int y;
Further more, when you define a static member, you need to define it again in the CPP file and initialize it with a value. It doesn't look like you're doing that and that's why you're getting the linker errors.
Also, next time you post something, make sure you actually ask a question rather than just simply stating facts.