在向量中找到高于阈值的连续值的最佳方法

时间:2015-09-17 22:05:33

标签: c++ algorithm vector

找到超过阈值的最小连续值的最快方法是什么?

假设我有一个值向量:

std::vector<int> v = [10 25 8 49 50 61 55 45 34 10 8]

一种简单的方法是迭代向量;

int threshold = 40;
int consecutive = 5;

bool success = false;

for(int i = 0; i < v.size()-consecutive; ++i)
{
    int counter = 0;

    while(i+counter < v.size())
    {
        if(v[i+counter] > threshold)
        {
            counter++;
        }
    }

    if(counter >= consecutive)
    {
        success = true;
        break;
    }
}

编辑:for @cmbasnett

如果在success = true向量5中找到40v个连续值,则预期结果为false

1 个答案:

答案 0 :(得分:2)

您可以使用std::search_n()执行此操作:

bool success = search_n(begin(v), end(v), 5, 40, [](int x, int y) { return y < x; }) != end(v);

Live version

你可以跳过一个失败的元素,有点像Boyer-Moore-Hoorspool搜索,从而更有效地编写自己的优化版本:

template<typename It, typename T>
bool contains_n_gt_x(It first, It last, size_t n, const T& x) {
    for (auto curr = first; first != last;) {
        first = find_if(curr, last, [&](const auto& y){ return x < y; });
        curr = find_if(first, last, [&](const auto& y){ return !(x < y); });
        if (distance(first, curr) >= n) return true;
    }
    return false;
}

Live version

相关问题