耦合比算法

时间:2014-03-01 11:15:44

标签: c++ algorithm

是否有标准的adlgorithm来执行以下操作?

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 !

我的测试运行良好

1 个答案:

答案 0 :(得分:3)

是的,有:

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一些评论

  • 你正在使用整数除法,对比率有什么好处? (您的结果将是1或0)
  • 您没有正确使用unique,删除相邻的重复项

    v.erase(std::unique(v.begin(), v.end()), v.end());
    
  • 强化转换不会解决您的问题,它只会自动抛出integer exception by zero。在你的情况下,你可能没有注意到一些无限