首页 > 解决方案 > 为索引找到最接近的真实值

问题描述

是否有一种优雅的 STL 方法可以true在给定索引的数组中找到最接近的 (1) 值。例如,对于给定索引 5std::vector<int> v{1,1,1,0,0,0,1,1,0};的最接近的true值在索引 6 处。

我尝试并最终使用了多个带有迭代器的 while 循环。是否可以使用 C++ STL?

标签: c++stl

解决方案


这是我能想到的最简洁的版本。

  • 用于cbegin从左->右和从右- crbegin()>左查找。但请注意,在后一种情况下,需要进行一些计算才能获得正确的起始位置。

您将需要C++17来支持if init 语句

#include <vector>
#include <iostream>
#include <algorithm>
#include <numeric>
int main()
{
    const std::vector<int> v{ 1, 1, 1, 0, 0, 0, 1, 1, 0 };

    const int index_to_find = 5;

    int rdistance = std::numeric_limits<int>::max();
    if (auto iter_right = std::find(std::cbegin(v) + index_to_find + 1, std::cend(v), 1); iter_right != std::cend(v))
        rdistance = std::distance(std::cbegin(v) + index_to_find, iter_right);

    int ldistance = std::numeric_limits<int>::max();
    if (auto iter_left = std::find(std::crbegin(v) + v.size() - index_to_find, std::crend(v), 1); iter_left != std::crend(v))
        ldistance = std::distance(std::crbegin(v) + v.size() - index_to_find - 1, iter_left);

    if (ldistance == std::numeric_limits<int>::max() && rdistance == std::numeric_limits<int>::max())
        std::cout << "Not found!\n";
    else
    {
        if (ldistance == rdistance)
            std::cout << "Found at index: " << index_to_find + ldistance << " and " << index_to_find - ldistance << "\n";
        else
            std::cout << "Found at index: " << (rdistance > ldistance ? index_to_find - ldistance : index_to_find + rdistance) << "\n";
    }
}

推荐阅读