C++ Accessing and Manipulating 2D Pointer Array from within get function - c++

I am making a battleships game for my coursework, and I have run into some problems with the get functions in one of the classes I am using. The basic idea of my game is to create a 2D 10X10 array, called grid, filled with null pointers to represent the board. I have created 2 classes, Board and Ship. The grid array is of type Ship, and I use an algorithm to fill the array with Ships randomly. I use the Board class to access the grid array and the hits array (which I use to track hits).
However I cannot figure out how the getShips function can return the grid array. The hits array is just booleans so that was easy enough, but I am not proficient enough at C++ to make the getShips function properly return the grid array, which is a Ship pointer type. I would greatly appreciate any help.
class Board
{
private:
Ship *grid[10][10];
bool hits[10][10];
public:
// get functions
Ship *getShips()
{
return grid;
}
bool getHits()
{
return hits;
}
};
I was also wondering if it would be possible to manipulate the array in other functions by calling the getShips function. Something like:
for (int x=0; x<10; x++)
{
for (int y=0; y<10; y++)
{
board.getShips()[x][y]=nullptr;
}
}

Ok. First I would modify the getShips and getHits functions. To have something like that :
Ship *getShips(int x, int y){ return grid[x+y*10]; }
bool getHits(int x, int y){return hits[x+y*10];}
That way you'll simplify your code and avoid some errors.
When you declare a multidimensional array like you do with
Ship *grid[10][10];
bool hits[10][10];
you're basically declaring pointers to pointers to pointers to ships.
I would try to use a minimum amount of pointers if you're writing in C++. Try to use the stl containers instead. They do automatic memory management for you which may save you some time down the road.

I suggest to change your interface to something like:
class Board
{
private:
Ship *grid[10][10];
bool hits[10][10];
public:
Ship* getShip(int x, int y) const { return grid[x][y]; }
Ship*& getShip(int x, int y) { return grid[x][y]; }
bool getHit(int x, int y) const { return hits[x][y]; }
bool& getHit(int x, int y) { return hits[x][y]; }
};
If you really want to return grid and hits, I recommend to use std::array<std::array<Ship*, 10>, 10> grid; (require C++11) instead of Ship *grid[10][10];.
if C++11 is not possible turn back to std::vector.
and then
private:
std::array<std::array<Ship*, 10>, 10> grid;
public:
const std::array<std::array<Ship*, 10>, 10>& getShips() const { return grid; }
std::array<std::array<Ship*, 10>, 10>& getShips() { return grid; }

Currently, it looks like getShips is returning the entire 10x10 array of Ship*-- you need to change what the getShips function is returning:
Ship*** getShips() { ...
However, I would recommend against mixing pointers and arrays. Pointers can be tricksy, and combining with arrays can get very difficult to debug. Instead, you could use all pointers: Ship ***grid; and initialize with new (I'll leave the initialization as an exercise, but here's a site that has an example: http://pleasemakeanote.blogspot.com/2010/07/2d-arrays-in-c-using-new.html).
In reality, it might be better for the Ship class to store the indices of where it exists, perhaps something like this:
class Ship
{
public:
<<member func>>
private:
int nspaces_;
int start_[2];
int end_[2];
}
where you store the beginning index and the final index where the ship is found. You'll need to handle the code to identify the spaces between, but that is trivial. This setup would allow you to replace Ship *grid[10][10] with a single array of Ships.
The getShips function would then become:
...
Ship ships_[<<number of ships>>];
Ship *getShips()
{
return ships_;
}
...
and would be used:
board.getShips()[x][y]
Or...you could add a getShip(int x, int y) method.

Related

Returning 2d array of pointers in c++

I have a class and another class with class member of 2d array from the first class type.
and I need a function that returns that class member.
class Piece
{
// something is implemented here/
};
class Board
{
private:
Piece* _pieces[8][8];
public:
Piece*** getPieces()
{
return _pieces;
}
}
but that's not working.
This is a quick version of your class I made to allow the passing of the 2d array to work.
class Board
{
private:
Piece ** _pieces = new Piece*[8];
public:
Board()
{
for(int i = 0; i<8; i++)
_pieces[i] = new Piece[8];
}
Piece** getPieces()
{
return _pieces;
}
~Board()
{
for(int i = 0; i<8; i++) delete [] _pieces[i];
delete [] _pieces;
}
};
You could std::array to create 2D array of pointers if you have access to C++11/14/17, it's a lot cleaner and expressive than using the build in array that decay to a ptr.
What follows is an example of how you create and return from Booard a 8x8 2D array of pointers to Pieces.
#include <array>
class Piece
{
// something is implemented here/
};
using Pieces=std::array<std::array<Piece*,8>,8>;
class Board
{
private:
Pieces _pieces;
public:
const Pieces& getPieces()
{
return _pieces;
}
};
As suggested by #Galik in comment, you should use std::arrays here, because the sizes are constant expressions.
It is not really mandated by the standard, but for common implementations, a std::array<std::array<T,i>,j> does have a true T[i][j] 2D array as underlying data - said differently, consecutive rows use adjacent memory. std::vector on another hand acts more as an array of pointers and data of consecutive rows are generally not adjacent in memory.
Code could become:
class Board
{
private:
std::array<std::array<Piece*, 8>, 8> _pieces;
public:
std::array<std::array<Piece*, 8>, 8>& getPieces()
{
return _pieces;
}
}
But this is still poor design, because it unnecessarily exposes the underlying implementation, so you really should think twice on what should be the public methods for the Board class.
for example,
int a[3][6];
int **p=a; // it's wrong
You should use pointer like this:
int (*p)[6];
p=a;

Multiple dot operator (c++ class)

I have to implement a class Vector, which sets coordinates of a multi-dimensional vector and will work when called with this specific code (I can't change this part):
const int NumOfDimensions = 5;
Vector x (NumOfDimensions);
x.Set(0, 1.1).Set(1, 1.2).Set(2, 1.3).Set(3, 1.4).Set(4, 1.5);
x.print();
and the output has to be like this:
(1.1, 1.2, 1.3, 1.4, 1.5)
This is what I tried but couldn't get it to work:
class Vector {
float *coordinates;
int dimensions;
public:
Vector(int k)
{
coordinates = new float[k];
dimensions = k;
}
void Set(int k, float wsp)
{
//Vector x(k+1);
coordinates[k] = wsp;
//return x;
}
void print()
{
int i;
cout<<"(";
for(i=0; i<dimensions; i++)
cout<<coordinates[i]<<", ";
cout<<")"<<endl;
}
};
So I know function Set needs to be changed and probably return an object but I have tried lots of different ways and it just doesn't work. How should I modify it?
If you want to be able to chain methods of that sort you need to return a reference:
Vector& Set(int k, float wsp) {
// ...
return *this;
}
I'd argue that even though you see a lot of that in other languages like Python, Ruby and so on, that interface isn't very C++.
You'd be better off using std::vector to store your coordinates, the C-style arrays are nothing but trouble. This code actually has a severe memory leak since you don't de-allocate with delete[], there's no destructor defined. Using a Standard Library container offloads that responsibility.
Another thing you can do to make this more natively C++ is to define a formatter for it so you can simply dump this to cout directly instead of having a clunky method called print which does it for you:
std::ostream& operator<<(std::ostream& stream, const Vector& vec);
That will permit the use of that formatter on any stream, not just cout.

How to return an array of structs from a class in a getter function

I have a relatively simple question but I cant seem to find an answer specific for my case and I just may not be approaching this problem the right way. I have a class that looks like this:
struct tileProperties
{
int x;
int y;
};
class LoadMap
{
private:
ALLEGRO_BITMAP *mapToLoad[10][10];
tileProperties *individualMapTile[100];
public:
//Get the struct of tile properties
tileProperties *getMapTiles();
};
I have an implementation that looks like this for the getter function:
tileProperties *LoadMap::getMapTiles()
{
return individualMapTile[0];
}
I have code in the LoadMap class that will assign 100 tile properties for each struct in the array. I want to be able to access this array of structs in my main.cpp file but I just cant seem to find the right syntax or approach. My main.cpp looks like this.
struct TestStruct
{
int x;
int y;
};
int main()
{
LoadMap _loadMap;
TestStruct *_testStruct[100];
//This assignment will not work, is there
//a better way?
_testStruct = _loadMap.getMapTiles();
return 0;
}
I realize that there are many approaches to this, but I'm trying to keep this implementation as private as possible. If someone could please point me in the right direction I would greatly appreciate it. Thank you!
TestStruct *_testStruct;
_testStruct = _loadMap.getMapTiles();
This will get you a pointer to the first element in the array returned. You can then iterate through the other 99.
I would highly recommend using vectors, or another container, and writing getters that don't return pointers to bare arrays like that.
First of all, here, why do we need TestStruct, you can use "tileProperties" structure itself...
And imp thing,
tileProperties *individualMapTile[100]; is array of pointers to the structure.
Hence, individualMapTile will have pointers in it.
You have returned the first pointer, hence you can access the first structure only. What about the others????
tileProperties** LoadMap::getMapTiles()
{
return individualMapTile;
}
int main()
{
LoadMap _loadMap;
tileProperties **_tileProperties;
_tileProperties = _loadMap.getMapTiles();
for (int i=0; i<100;i++)
{
printf("\n%d", (**_tileProperties).x);
_tileProperties;
}
return 0;
}
Use vectors instead of arrays where possible. Also consider an array/vector of TestStruct directly rather than pointers to them. I can't tell if that would be appropriate for you from your code sample.
class LoadMap
{
public:
typedef vector<tileProperties *> MapTileContainer;
LoadMap()
: individualMapTile(100) // size 100
{
// populate vector..
}
//Get the struct of tile properties
const MapTileContainer& getMapTiles() const
{
return individualMapTile;
}
MapTileContainer& getMapTiles()
{
return individualMapTile;
}
private:
MapTileContainer individualMapTile;
};
int main()
{
LoadMap _loadMap;
LoadMap::MapTileContainer& _testStruct = _loadMap.getMapTiles();
}

VBO of std::vector<MyClass*> and correct strides

I'm wondering how to get the maximum data locality and performance for the following problem without data copy.
I've a std::vector< MyClass* > where MyClass is something like
class MyClass
{
public:
MyClass(int n,double px,double py,double pz)
{
someField=n;
x=px;
y=py;
z=pz;
anotherField=100;
anotherUnusefulField=-10.0;
}
int someField;
int anotherField;
double x;
double y;
double z;
double anotherUnusefulField;
};
std::vector<MyClass*> myClassVector;
// add some values and set x,y,z
for (std::vector<MyClass*>::iterator iter = myClassVector.begin(); iter!=myClassVector.end();++iter)
{
MyClass *tmp = *iter;
tmp->x+=1.0;
tmp->y+=2.0;
tmp->z+=3.0;
}
I'm iterating frequently on these data and I also would like to enforce data locality. The data contained in the pointer to MyClass should be sent to a OpenGL vertex array, where the vertices are ONLY determined by x,y,z variables. As you may imagine is difficult to correctly set the strides, so I'm here to ask if there are other (portable) solution to this problem.
(p.s. I've already read the post VBOs with std::vector but my case is basically different because I have pointers and I also have other variables inside the class.)
I have pointers
Those pointers are useless to OpenGL, as they're in client address space. Also OpenGL doesn't dereference second level pointers.
and I also have other variables inside the class.
Well, then don't do this. If you passed those class instances to OpenGL you'd copy a lot of useless data. I recommend you just store a index into a tightly packed std::vector or array in your class members, and a reference to the vector/array itself. You can use getter/setter/referencer member functions to abstract away the access to the vector, i.e.
class …
{
// …
std::vector<v_t> *v;
size_t index_v;
x_t getX() const { return (*v)[index_v]; }
x_t setX(x_t x) { return (*v)[index_v] = x;}
x_t &x() { return (*v)[index_v]; }
};

Function that returns a pointer to const 2-d array (C++)

I'm an intermittent programmer and seem to have forgotten a lot of basics recently.
I've created a class SimPars to hold several two-dimensional arrays; the one shown below is demPMFs. I'm going to pass a pointer to an instance of SimPars to other classes, and I want these classes to be able to read the arrays using SimPars accessor functions. Speed and memory are important.
I know life is often simpler with vectors, but in this case, I'd really like to stick to arrays.
How do I write the accessor functions for the arrays? If I'm interested in the nth array index, how would I access it using the returned pointer? (Should I write a separate accessor function for a particular index of the array?) What's below is certainly wrong.
// SimPars.h
#ifndef SIMPARS_H
#define SIMPARS_H
#include "Parameters.h" // includes array size information
class SimPars {
public:
SimPars( void );
~SimPars( void );
const double [][ INIT_NUM_AGE_CATS ] get_demPMFs() const;
private:
double demPMFs[ NUM_SOCIODEM_FILES ][ INIT_NUM_AGE_CATS ];
};
#endif
// SimPars.cpp
SimPars::SimPars() {
demPMFs[ NUM_SOCIODEM_FILES ][ INIT_NUM_AGE_CATS ];
// ...code snipped--demPMFs gets initialized...
}
//...destructor snipped
const double [][ INIT_NUM_AGE_CATS ] SimPars::get_demPMFs( void ) const {
return demPMFs;
}
I would greatly appreciate some kind of explanation with proposed solutions.
Basically, you have three options: return the entire array by reference, return the first row by pointer, or return the entire array by pointer. Here is the implementation:
typedef double array_row[INIT_NUM_AGE_CATS];
typedef array_row array_t[NUM_SOCIODEM_FILES];
array_t demPMFs;
const array_t& return_array_by_reference() const
{
return demPMFs;
}
const array_row* return_first_row_by_pointer() const
{
return demPMFs;
}
const array_t* return_array_by_pointer() const
{
return &demPMFs;
}
And here are the use cases:
SimPars foo;
double a = foo.return_array_by_reference()[0][0];
double b = foo.return_first_row_by_pointer()[0][0];
double c = (*foo.return_array_by_pointer())[0][0];
How would I return just the nth row of the array?
Again, you have three choices:
const array_row& return_nth_row_by_reference(size_t row) const
{
return demPMFs[row];
}
const double* return_first_element_of_nth_row_by_pointer(size_t row) const
{
return demPMFs[row];
}
const array_row* return_nth_row_by_pointer(size_t row) const
{
return demPMFs + row;
}
const double (* get_demPMFs() const)[INIT_NUM_AGE_CATS];
Or, use typedef (but that doesn't seems cleaner...).
class SimPars {
typedef const double (*ConstDemPMFType)[INIT_NUM_AGE_CATS];
double demPMFs[NUM_SOCIODEM_FILES][INIT_NUM_AGE_CATS];
public:
ConstDemPMFType get_demPMFs() const;
};
Note that you can't return an array (g++ refuses the compile). But an array of array can be decayed to a pointer to array, so the latter is returned.
Logically speaking there is this question with a data member. Should users be allowed to modify it or not. If you want to give another class full access to the member, you don't necessarily need getter/setter, especially if you are the only user. You can just make the member public.
If your class would be better off controlling how users access the member, then you could use a getter only to enforce read only access. The simplest way to do this if you don't want to get all confused about the 2-dimensional arrays is to just have an inline function fetching the element for the user class:
const double& getElem( int x, int y ) const { return demPMF[x][y] }
It makes sense to do bounds checking here, but considering that you insist on using arrays, and if your profiler proves that you can't afford it, this function would just allow access to your array.
If you want further elaboration, post a comment...