首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >耦合比算法

耦合比算法
EN

Stack Overflow用户
提问于 2014-03-01 11:15:43
回答 1查看 47关注 0票数 0

是否有执行下列操作的标准算法?

代码语言:javascript
复制
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 ):

代码语言:javascript
复制
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;
}

有趣的是,如果我写了像这样的错误发送行

代码语言:javascript
复制
std::cout << 1 / (double)(v.at(i+1) - v.at(i)) << std::endl; // NO ERROR !

我的测试运行良好

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-03-01 11:22:22

是的有:

代码语言:javascript
复制
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::唯一性(v.begin(),v.end()),v.end());
  • “强制转换为双”不会解决您的问题,只会自动抛出integer exception by zero。在你的例子中,可能有一些你没有注意到的无穷大
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22113628

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档