Sign in to follow this  
Headkaze

Move element in std::vector

Recommended Posts

I need to move an object in a vector.

Here is what I have so far based on some code I found on the Net. Unfortunatey when I try to move it from index 0 to 4 it ends up at index 3.

[code]void Pile::MoveCard(Card *card, int index)
{
DEBUGLOG("MOVECARD: CurrentIndex: %d InsertIndex: %d Count: %d", GetCardIndex(card), index, m_cardArray.size());
vector<Card *>::iterator currentIndex = m_cardArray.begin() + GetCardIndex(card);
vector<Card *>::iterator insertIndex = m_cardArray.begin() + index;

if (currentIndex < insertIndex)
rotate(currentIndex, currentIndex+1, insertIndex);
else
rotate(insertIndex, currentIndex, currentIndex+1);

DEBUGLOG("MOVECARD: CurrentIndex: %d", GetCardIndex(card));
}[/code]

Output is

[code]MOVECARD: CurrentIndex: 0 InsertIndex: 4 Count: 5
MOVECARD: CurrentIndex: 3[/code]

It should be at index 4.

Share this post


Link to post
Share on other sites
Thanks. This appears to work.

[code]void Pile::MoveCard(Card *card, int index)
{
vector<Card *>::iterator currentIndex = m_cardArray.begin() + GetCardIndex(card);
vector<Card *>::iterator insertIndex = m_cardArray.begin() + index;

if (currentIndex < insertIndex)
rotate(currentIndex, currentIndex+1, insertIndex+1);
else
rotate(insertIndex, currentIndex, currentIndex+1);
}[/code]

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this