c++ - 为索引找到最接近的真实值
问题描述
是否有一种优雅的 STL 方法可以true
在给定索引的数组中找到最接近的 (1) 值。例如,对于给定索引 5std::vector<int> v{1,1,1,0,0,0,1,1,0};
的最接近的true
值在索引 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";
}
}
推荐阅读
- git - 如何在 Git Bash 中找出特定分支中文件的文件路径?
- python - 无法从“变压器”导入名称“TFBertForQuestionAnswering”
- segmentation-fault - for 循环中 J 的随机值且不执行终止
- dialogflow-es - 此设备不支持 HtmlResponse
- amazon-web-services - 如何在 AWS 中备份 IAM 用户
- android - 从子片段更新操作栏标题
- javascript - 我将如何使用 for 循环而不是使用 [...Array].map() 方法重写此代码?
- spring - 自定义招摇文档/我招摇设置在哪里?
- sql - 在 Oracle 中将带时区的 Varchar 转换为时间戳
- c# - 使用 C# 在 oData 客户端中使用带有延续的 where 子句