是否有执行下列操作的标准算法?
void DifferenceRatioWithNext(std::vector<int> const &v)
{
for (int i(0); i < v.size()-1; ++i)
{
std::cout << 1 / (v.at(i+1) - v.at(i)) << std::endl; // ERROR !
// I 'm printing but when complete I'd like to store my results in a container
}
}我认为它可以正常工作,但是当尝试测试它时,会弹出除以零异常(即使调用方使用了unique ):
int main()
{
std::vector<int> v;
// test on 100 random datasets of magnitude=10
for (int j = 0; j < 100; j++)
{
srand(0);
for (int i(0); i < 10; ++i) {
v.push_back(rand()%10);
}
std::unique(v.begin(), v.end());
DifferenceRatioWithNext(v);
v.clear();
}
return 0;
}有趣的是,如果我写了像这样的错误发送行
std::cout << 1 / (double)(v.at(i+1) - v.at(i)) << std::endl; // NO ERROR !我的测试运行良好
发布于 2014-03-01 11:22:22
是的有:
std::adjacent_difference(v.begin(), v.end(), std::back_inserter(result),
[](int rhs, int lhs) {
return 1 / double(rhs-lhs); // attention, lhs is the previous element!
});但是,在这个实现中,它是DifferenceRatioWithPrev。关于的几点评论
unique,以删除相邻的重复
V.erase(std::唯一性(v.begin(),v.end()),v.end());integer exception by zero。在你的例子中,可能有一些你没有注意到的无穷大https://stackoverflow.com/questions/22113628
复制相似问题