I am trying to move the last element of the vector old_balls
to the new vector new_balls
.
But when I call the function, it doesn't move the element to the new vector.
I think I am using the move function correctly.
std::vector<ball*> old_balls;
std::vector<ball*> new_balls;
void move(std::vector <ball*> ball_box, std::vector <ball*> n_ball_box ){
new_ball_.push_back(std::move(ball_box[0]));
}
//function call
move(old_balls, new_balls);
UPDATE: with the below code, I expect new_balls
to have one element of old_balls
, but I get a buffer overflow:
Balls.hpp
Private:
std::vector<ball*> new_balls;
void move(std::vector<ball*> ball_box)
{
ball* b = ball_box.front();
ball_box.erase(ball_box.begin());
new_balls.push_back(b); //don't have to pass new ball because it's member variable
}
This is how I call the function in Main.cpp
:
std::vector<ball*> old_balls; //This has 30 ball* elements.
...
ball object;
object.move(old_balls);
You are passing the vectors by value, so you are acting on copies of the vectors, not on the original vectors. You need to pass the vectors by reference instead.
Also, you said you wanted to move the last element, but you are actually moving the first element instead. And you are not removing the element from the old vector.
Also, there is no need to use std::move()
with raw pointers. Why are you using ball*
at all? You should be using std::unique_ptr<ball>
instead.
Try something more like this:
void move(std::vector<ball*> &ball_box, std::vector<ball*> &n_ball_box)
{
ball* b = ball_box.back();
ball_box.pop_back();
n_ball_box.push_back(b);
}
If you really want to move the first element, then it would look like this instead:
void move(std::vector<ball*> &ball_box, std::vector<ball*> &n_ball_box)
{
ball* b = ball_box.front();
ball_box.erase(ball_box.begin());
n_ball_box.push_back(b);
}
That said, if you switch to std::unique_ptr<ball>
, then it would look more like this:
using ball_ptr = std::unique_ptr<ball>;
void move(std::vector<ball_ptr> &ball_box, std::vector<ball_ptr> &n_ball_box)
{
ball_ptr b = std::move(ball_box.back());
ball_box.pop_back();
/* or:
ball_ptr b = std::move(ball_box.front());
ball_box.erase(ball_box.begin());
*/
n_ball_box.push_back(std::move(b));
}
std::vector<ball_ptr> old_balls;
std::vector<ball_ptr> new_balls;
...
move(old_balls, new_balls);