Search code examples
c++c++11pointersvectormove

Using std::move to insert middle element of a vector at the beginning not working


I have a vector with a few elements. I tried to insert one of its own element, at the beginning using insert and move -

v.insert(v.begin(), std::move(v[4]));

This inserted the wrong element to the beginning. Complete code -

#include <iostream>
#include <vector>

using namespace std;

struct Node
{
    int* val;
};

// Util method which prints vector
void printVector(vector<Node>& v)
{
    vector<Node>::iterator it;

    for(it = v.begin(); it != v.end(); ++it)
    {
        cout << *((*it).val) << ", ";
    }

    cout << endl;
}

int main() {
    vector<Node> v;

    // Creating a dummy vector
    v.push_back(Node()); v[0].val = new int(0);
    v.push_back(Node()); v[1].val = new int(10);
    v.push_back(Node()); v[2].val = new int(20);
    v.push_back(Node()); v[3].val = new int(30);
    v.push_back(Node()); v[4].val = new int(40);
    v.push_back(Node()); v[5].val = new int(50);
    v.push_back(Node()); v[6].val = new int(60);

    cout << "Vector before insertion - ";
    printVector(v); // Prints - 0, 10, 20, 30, 40, 50, 60,

    // Insert the element of given index to the beginning
    v.insert(v.begin(), std::move(v[4]));

    cout << "Vector after insertion - ";
    printVector(v); // Prints - 30, 0, 10, 20, 30, 40, 50, 60,
    // Why did 30 get inserted at the beggning and not 40?

    return 0;
}

Ideone link - https://ideone.com/7T9ubT

Now, I know writing it differently will make sure I get the right value inserted. But what I specifically want to know is why didn't this work -

v.insert(v.begin(), std::move(v[4]));

And how (in my code above) did value 30 get inserted to the vector beginning? Thanks in advance! :)


Solution

  • v[4] is a reference to an element of the vector. insert invalidates all references and iterators to elements past the insertion point (all of them in your example). So you get undefined behavior - the reference is no longer valid somewhere inside the insert function.