int main(){
std::vector<int> vec;
vec.push_back(1);
vec.push_back(2);
vec.push_back(vec[0]);
for (auto it = vec.begin(); it != vec.end(); it++) {
std::cout << *it << std::endl;
}
return 0;
}
This outputs [1, 2, 1], which I understand because the vector is making a copy of vec[0] and pushing it back. However, I would like the output to be like [2, 1] and was curious if I can accomplish this without using push_back() and then having to use erase();
The goal: I want to be able to move an element in the vector to the end while the vector adjusts itself accordingly, so if I move an element at the 5th position to the end, all the elements after the original 5th position would move up, so the new 5th position would have the element at the old 6th position and so forth.
You are probably looking for std::rotate
.
int main() {
//Fill vector
std::vector<int> vec;
vec.push_back(1);
vec.push_back(2);
vec.push_back(3);
//move first element to the end
std::rotate(vec.begin(), vec.begin() + 1, vec.end());
//print content
for (auto e:vec) {
std::cout << e << std::endl;
}
}
Explanation for the parameters:
Essentially, you can see the the distance between the second and the first parameter (here 1
) as the number of elements, by which the range gets shifted.