使用 std::move 在开始时插入矢量的中间元素不起作用
Using std::move to insert middle element of a vector at the beginning not working
我有一个包含几个元素的向量。我尝试插入它自己的元素之一,一开始使用插入和移动 -
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
函数内的某个地方不再有效。
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 2D数组来自文本输入,中间有空格
- 使用strcpy将char数组的元素复制到另一个数组
- 使用不带参数的函数访问结构元素
- 如何输入数组的元素,每次获得新元素时,我们将其放在数组的中间?
- C++:我可以重用/移动 std::list 元素从中间到结尾吗?
- 如何使用第一个、中间和最后一个元素的中位数正确分区?
- 使用 std::move 在开始时插入矢量的中间元素不起作用
- 当中间元素选择为枢轴时,快速排序C 不起作用
- 将元素插入到中间的矢量中
- 如何更改元素中间的文本样式
- std::multiset并查找中间元素
- 在合并排序中选择中间元素
- 删除单链表中间的元素
- 从中间删除元素的最佳数据结构是什么
- TinyXML2 -在XML中间插入元素
- 使用中间元素作为透视C++计算快速排序中的比较数
- 对于可移动类型,删除std::向量中间的元素仍然很昂贵吗
- 如何找到地图的中间元素??STL