是否有一种 STL 算法可以最后找到,但它也适用于指针?
Is there a STL algorithm that finds last but that it also works on pointers?
我有现有的代码,我无法切换到迭代器。 如果可能的话,我仍然想使用 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::find
和reverse_iterator
s(对于双向容器(,就像您尝试过的那样,但 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);
相关文章:
- 1d 智能指针不适用于语法 (*)++
- FLTK 2.0构建和演示,适用于VS2019的2011年左右的代码库
- C++17 - 使用自定义分配器的节点提取/重新插入 - 适用于 clang++/libc++,但不适用于 libstd
- "string.h"在构建适用于iOS的qt应用程序中找不到消息
- 适用于 WebView2 旧版本的示例应用程序
- std::byte 指针应该用于指针算术吗?
- 在 NVIDIA GEFORCE GTX 1050 上下载适用于 Windows 10 的 openCL 1.2
- __attribute__(优化(0))) 是否适用于"recursively"?
- 为什么 std::erase(std::erase_if) 不是适用于<algorithm>任何容器的模板?
- 使用一个参数的模板函数时出错(适用于 2)
- 使用 适用于 Android 和 iOS 的 tf-lite C++ API
- 下步指针键入用于shared_ptr的级别
- 为什么这适用于 G++ 而不是 CLANG?
- 适用于 macOS 的 Xcode 应用程序。这就是我设置从USB麦克风输入获取音频的方式。一年前工作,现在没有了。为什么
- 适用于 Linux 的 c++ 上的代理脚本
- 为什么我的 SFINAE 表达式不再适用于 GCC 8.2?
- Lambda 到函数指针适配器的理解
- 访客模式适用于shared_ptr或原始指针?
- 函数指针数组的类模板参数推导适用于 clang,但不适用于 gcc
- C++指针到方法模板推导在面向 x86 时不编译,但适用于 x64