Search code examples
c++vectorerasepush-back

How can I move an element to the end of a vector?


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.


Solution

  • 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:

    • The first and last parameter denote the range of all elements that will be moved around (so here the whole container).
    • The second parameter is an iterator to the element that lands on the first position after the rotate. When you want to move the first element to the end, the second one is the one (index 1) to move to the front.

    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.