gpt4 book ai didi

c++ - 为索引寻找最接近的真实值

转载 作者:行者123 更新时间:2023-12-01 12:48:29 28 4
gpt4 key购买 nike

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

我尝试并最终使用了多个带有迭代器的 while 循环。是否可以使用 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";
    }
    }

    关于c++ - 为索引寻找最接近的真实值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60023221/

    28 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com