我试图插入现有的vector
元素的副本来将其加倍。下面的代码曾在以前的版本中,但在Visual Studio 2010失败如何将重复元素插入到矢量中?
#include <iostream>
#include <vector>
using namespace std;
int main(int argc, char* argv[])
{
vector<int> test;
test.push_back(1);
test.push_back(2);
test.insert(test.begin(), test[0]);
cout << test[0] << " " << test[1] << " " << test[2] << endl;
return 0;
}
输出是-17891602 1 2
,预计1 1 2
。
我已经知道为什么会发生这种情况 - 矢量正在被重新分配,并且在复制到插入点之前引用变为无效。较早的Visual Studio显然是以不同的顺序做了事情,从而证明未定义行为的一个可能结果是正确工作,并且证明它绝不是你应该依赖的东西。
我想出了两种不同的方法来解决这个问题。一种是使用reserve
以确保没有重新分配发生:
test.reserve(test.size() + 1);
test.insert(test.begin(), test[0]);
另一种是使从参考副本,以便有一个在参考其余没有依赖有效:
template<typename T>
T make_copy(const T & original)
{
return original;
}
test.insert(test.begin(), make_copy(test[0]));
虽然既工作,也没有人觉得自然的解决方案。有什么我失踪?
BTW vc11 dev预览给出了第一个例子中的'1 1 2'。 – 2012-04-18 21:28:54
@Jesse,这并不让我感到意外。正在选择'insert'的Rvalue重载,这看起来像是他们可能已经修复的错误。该代码在超载和采用const引用的代码之间完全不同。 – 2012-04-18 21:32:24
是否投射到int工作? – 2012-04-18 21:35:50