【发布时间】:2014-08-01 00:34:59
【问题描述】:
今天我在玩一些标准库函数.. 并且发现每当容器正在使用(在本例中为向量)中包含超过 2 个元素时 std::transform() 和 std::back_inserter 的这个奇怪输出.我不明白这种行为那里的任何人都可以帮助我......
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
/* this version of change works fine for me when i store the incoming value into a
static variable
int change(int n){
static int m=n;
return m * m;
}*/
int change(int n){
return n*n;
}
int main(){
vector<int> v2(3,3),
v1;
transform(v2.begin(),v2.end(),back_inserter(v2),change);
for(auto v: v2)
{
cout << v <<" "; // prints out a strange random 5th value in v2.
}
return 0;
}
【问题讨论】:
-
当容器用作算法的输入时,通常不允许在算法执行期间修改容器或使迭代器无效。
-
请避免在代码块中出现长行。不是每个人都在配备超宽显示器的台式机上使用最大化的浏览器查看这些页面。
-
顺便说一句:UB has a time-machine,因此由于程序在任何可能的执行过程中都会遇到它,因此程序从一开始就具有未定义的行为。