使用 std::move 在开始时插入矢量的中间元素不起作用

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

本文关键字:中间 元素 不起作用 插入 std move 开始时 使用      更新时间:2023-10-16

我有一个包含几个元素的向量。我尝试插入它自己的元素之一,一开始使用插入和移动 -

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

这会在开头插入错误的元素。完整代码 -

#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

现在,我知道以不同的方式编写它将确保我插入正确的值。但我特别想知道的是为什么这不起作用——

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

以及(在我上面的代码中(如何将值30插入到向量开头?提前感谢!:)

v[4]是对向量元素的引用。 insert使对超过插入点的元素的所有引用和迭代器无效(示例中的所有引用和迭代器(。所以你会得到未定义的行为 - 引用在 insert 函数内的某个地方不再有效。