Removing items containing references from a std::vector

I have a vector that holds references to animations, something like:

1
2
3
4
5
6
7
8
class SwapAnimation {
    Sprite &first;
    Sprite &second;
public:
    SwapAnimation(Sprite &first, Sprite &second);

    bool isDone();
}


I used the following code to actually remove the value:

1
2
3
4
std::vector<SwapAnimation> animations;
animations.erase(std::remove_if(animations.begin(), animations.end(), [](auto &animation) {
    return animation.isDone();
}), animations.end());


This however produces the error 'non-static reference member, can't use default assignment operator'.

I have worked around this by using pointers, but ideally I would prefer to avoid them entirely. Is it possible to somehow achieve this?
In order to "remove" the vector elements the algorithm needs to be able to copy them to a different location. But once a reference is set you can't change the object it refers to. Since your class has at least one reference member the copy assignment operator is implicitly deleted.

You could add a copy assignment operator that copies the value of one referenced object to another if that's feasible. But, if you want to stick with a vector, you may as well just use pointers (or unique_ptr or shared_ptr).

Alternatively, you could use a list (or forward_list, which is more efficient if you don't need it to be doubly-linked) instead of a vector since list elements don't need to be moved around when removed.
thanks, I've switched to forward_list, as it fits perfectly in my existing solution.
Topic archived. No new replies allowed.