Jump to content
  • Advertisement
Sign in to follow this  
Headkaze

Move element in std::vector

This topic is 2448 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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.

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));
}


Output is

MOVECARD: CurrentIndex: 0 InsertIndex: 4 Count: 5
MOVECARD: CurrentIndex: 3


It should be at index 4.

Share this post


Link to post
Share on other sites
Advertisement
Like every algorithm in the standard library, ranges specified by iterators are open at the end. You need to add one to the last iterator if you want to include that item in the rotation.

Share this post


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

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);
}

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!