【问题标题】:Using std::move to insert middle element of a vector at the beginning not working使用 std::move 在开头插入向量的中间元素不起作用
【发布时间】:2019-10-23 14:47:15
【问题描述】:

我有一个包含几个元素的向量。我尝试在开始时使用 insert 和 move 插入它自己的元素之一 -

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 链接 - https://ideone.com/7T9ubT

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

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

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

【问题讨论】:

  • 如果您不关心,msvc 19.00.24215.1 会提供Vector after insertion - 40, 0, 10, 20, 30, 40, 50, 60,

标签: c++ c++11 pointers vector move


【解决方案1】:

v[4] 是对向量元素的引用。 insert 使对插入点之后的元素的所有引用和迭代器(所有这些都在您的示例中)无效。所以你会得到未定义的行为 - 引用在 insert 函数中的某处不再有效。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-14
    • 1970-01-01
    • 2019-07-14
    • 1970-01-01
    • 2019-05-23
    相关资源
    最近更新 更多