Sorting std::vectors

Started by
6 comments, last by DejaimeNeto 10 years, 4 months ago

Hello, I am making a picture matching game(you have a picture and a jumbled picture and you need to make them match), and so I have a vector of tiles(2d squares with colour). When I move the selected tile it changes the position of the tile it moved onto to its old position. However, this does not change its position in the vector so when trying to see if the picture matches the one I just made, it doesn't work. I need a way to, after I move the tile, update the vector so the order of the tiles in the map is 0 - n and it isn't all jumbled up. I tried std::sort but that doesn't seem to work. Thanks for any help.I included a pic to help demonstrate the movement.[attachment=19165:Problem.png]

Advertisement

Maybe you need to implement some comparison operators for whatever you are sorting? (<, >, ==)

Can you explain "doesn't seem to work", and show what you tried with std::sort?

When I have the image the same as the one on the right, it should say I win, but it doesn't. I believe it is because of the order of the vector. I want the top corner of the map to be 0 and then all the way down to the bottom right to be n in a sequential order, despite how I move the tiles. At the beginning of the game i shuffle the tiles using std::random_shuffle and reset the positions so it is jumbled and call std::sort:


std::random_shuffle(m_blocks.begin(), m_blocks.end());

//reset the positions
for(int y = 0; y != 10; ++y){
	for(int x = 0; x != 10; ++x){
		m_blocks[(y * 10) + x]->setPos(sf::Vector2f(offsetX + (x * 32), offsetY + (y * 32)));
	}
}	

std::sort(m_blocks.begin(), m_blocks.end());

m_blocks is the tiles and 32 is the size of the block.

I also call std:;sort after I move the tiles:


std::sort(m_blocks.begin(), m_blocks.end());

Also I am overloading the < operator:


bool Block::operator<(Block& rhs){
	return (m_tile_pos < rhs.m_tile_pos);
}

and the m_tile_pos is set everytime the block is updated

How about you give each block a member int for its default position, then before shuffling them run through them all setting the values from 0 to n, then when you want to check the player has won just run a loop through the vector checking if 0 to n is the same as the position value of each block.

You should try debugging this and checking the contents of the vector after every iteration.. that might explain whats going on?

I fixed the issue two days ago, sorry for not commenting. I added a tilepos int and then wrote a predicate to pass into the std;:sort and that fixed it. Thanks for the responses.

You could take a look at std::map and std::multimap if you haven't already.

They may fit this better than an std::vector, but I didn't really read your code, so I'm not saying it for sure.

Still, it is always good to know they exist and how they work and how to use!

This topic is closed to new replies.

Advertisement