是否有一种 STL 算法可以最后找到,但它也适用于指针?

Is there a STL algorithm that finds last but that it also works on pointers?

本文关键字:指针 适用于 最后 一种 算法 STL 是否      更新时间:2023-10-16

我有现有的代码,我无法切换到迭代器。 如果可能的话,我仍然想使用 STL 来找到最后一项(如果您认为我们正在从末尾迭代,则首先(。 这可能吗?

std::find_end除了命名最差的算法之外,使用起来似乎很丑陋(我需要一个假的 1 元素序列和二进制谓词,相比之下忽略 1 个元素的值(。

我现在拥有的非常丑陋(特别是因为布尔*的反转不是布尔*,所以我必须做丑陋的事情才能得到std::d istance。

#include <algorithm>
#include <iostream>
int main()
{ 
{
bool arr[6] = {true,false,true,true,true,false};
auto e = std::make_reverse_iterator(&arr[0]);
auto b = std::make_reverse_iterator(&arr[6]);
auto it = std::find(b,e, false);
if (it!=e){
std::cout << "index of last false is " << &(*it) - &arr[0] << std::endl;
}
}
// repeat test to make sure result is not an accident
{
bool arr[6] = {true,false,true,true,false,true};
auto e = std::make_reverse_iterator(&arr[0]);
auto b = std::make_reverse_iterator(&arr[6]);
auto it = std::find(b,e, false);
if (it!=e){
std::cout << "index of last false is " << &(*it) - &arr[0] << std::endl;
}
}
}

查找容器中最后一个元素(包括 c 数组(索引的正确方法是使用std::findreverse_iterators(对于双向容器(,就像您尝试过的那样,但 UB 较少(&arr[6]是 UB(。

using std::begin;
using std::rbegin;
using std::rend;
bool arr[6] = {...};
auto it = std::find(rbegin(arr), rend(arr), false);
if (it != rend(arr)) {
auto idx = std::distance(begin(arr), it.base()) - 1;
std::cout << "idx is " << idx << std::endl;
}

我不确定我是否得到了你需要的东西,但这段代码似乎工作正常:

int arr[6] = { 1, 2, 3, 4, 5 };
int pattern[1] = { 4 };
auto it = std::find_end(arr, arr + 5, pattern, pattern + 1);