replicant
replicant

Reputation: 329

Changing between iterating forward and reverse

I have a animation class which stores the frames in a std::list, the header file declares a iterator, I increment the iterator using time. My animations are working fine until I try to reverse the animation (from the current position), I can't decrement the iterator (bidirectional huh?). I've thought about storing a reverse iterator too but can't find a nice way to switch between the two.

How can I seamlessly switch between forward iterating and reverse iterating (without starting from the beginning of the std::list).

Upvotes: 0

Views: 302

Answers (2)

Mike Seymour
Mike Seymour

Reputation: 254771

You should be able to decrement a list iterator; without seeing your code, and the error it produces, I can't guess what's going wrong there.

However, it might be more convenient to represent an animation as a generic iterator range:

template <typename ForwardIterator>
void animate(ForwardIterator start, ForwardIterator end)
{
    for (; start != end; ++start) {
        start->display();
    }
}

std::vector<frame> animation = ...;
animate(animation.begin(), animation.end());   // play forwards
animate(animation.rbegin(), animation.rend()); // play backwards

Upvotes: 1

Branko Dimitrijevic
Branko Dimitrijevic

Reputation: 52157

What do you mean "I can't decrement the iterator"?

On my Visual C++ 2010, this works:

std::list<int> l;
l.push_back(1);
l.push_back(2);
l.push_back(3);

auto i = l.end();
while (i != l.begin()) {
    --i;
    std::cout << *i << std::endl;
}

Upvotes: 0

Related Questions