Page 1 of 1

Vector problem

Posted: May 15th, 2017, 8:57 am
by Asfodel
Vector of objects, each element in vector contains:
position.x, position.y, color, type... bla bla

after matching some conditions i need to change position.x and position.y in one of the objects in vector. How to change that?

Re: Vector problem

Posted: May 15th, 2017, 9:12 am
by chili
Not sure what the problem is. Maybe show us some code.

It sounds like you should just use the [] operator on the vector to access and change the object.

Re: Vector problem

Posted: May 15th, 2017, 9:32 am
by Asfodel
Im trying to make chess game:

Code: Select all

**Piece.h**
enum PIECE_TYPE
{
	ROOK,KNIGHT, BISHOP, QUEEN, KING, PAWN
};

enum PIECE_COLOR
{
	BLACK, WHITE
};

struct PieceCoordinatesOnBoard
{
	int x;
	int y;
};

class Piece
{
public:
	Piece();
	~Piece();

	void initGame();

	PIECE_TYPE type;
	PIECE_COLOR color;
	PieceCoordinatesOnBoard position;
	PieceCoordinatesOnBoard destination;

	std::vector<Piece*> figurice;

Code: Select all

from -> **Game.cpp**

void Game::moveSelectedPiece(Piece &piece)
{

	piece.destination.x = piece.getRightClickX();
	piece.destination.y = piece.getRightClickY();

	for (size_t i = 0; i < piece.figurice.size(); i++)
	{
		int posX = piece.figurice[i]->position.x;
		int posY = piece.figurice[i]->position.y;

		if (posX == piece.getLeftClickX() && posY == piece.getLeftClickY())
		{
			if (isPieceMoveValid(piece.figurice[i], piece.destination) == true)
			{
				posX = piece.destination.x;
				posY = piece.destination.y;

				/*piece.figurice.push_back(piece.figurice[i]);*/
					
			}
		}
	}
when i debug its all ok till last part when it need to change coordinates of selected element in vector. It always stays on starting coordinates.
I have all 32 pieces on board stored in vector "figurice".

Re: Vector problem

Posted: May 15th, 2017, 10:00 am
by LuisR14
push_back just adds *new* elements to the vector, so instead just do:

Code: Select all

piece.figurice[i]->position.x = piece.destination.x;
piece.figurice[i]->position.y = piece.destination.y;

Re: Vector problem

Posted: May 15th, 2017, 10:36 am
by Asfodel
thanks

Re: Vector problem

Posted: May 15th, 2017, 12:06 pm
by chili
Why does Piece contain a vector of pointers to piece?

Re: Vector problem

Posted: May 15th, 2017, 8:05 pm
by Asfodel
oh... didn't think about that, it should be outside?

Re: Vector problem

Posted: May 16th, 2017, 1:03 am
by LuisR14
yea, what chili said after noticing him hehe (had only overlooked before)

Re: Vector problem

Posted: May 16th, 2017, 9:54 am
by Asfodel
ok, thanks! Hope i'll finish this game in day or two and post code here, if someone have any tip, suggestion, advice how to improve, i'll appreciate that.