gpt4 book ai didi

c++ - 如何在 C 风格数组上使用 find_if 和 reverse_iterator?

转载 作者:可可西里 更新时间:2023-11-01 15:52:07 25 4
gpt4 key购买 nike

要使用 POD 元素搜索 C 数组中元素的第一次出现,可以使用 std::find_if(begin, end, findit) 轻松实现。但我需要最后一次出现。 This answer让我想到这可以用 std::reverse_iterator 来完成。因此我尝试了:

std::find_if(std::reverse_iterator<podtype*>(end),
std::reverse_iterator<podtype*>(begin),
findit);

这给了我错误:

cannot convert 'std::reverse_iterator< xyz* > ' to 'xyz*' in assignment

您知道如何以这种方式做到这一点,或者您知道更好的解决方案吗?

这是代码:

#include <iostream>
#include <iterator>
#include <algorithm>

struct xyz {
int a;
int b;
};

bool findit(const xyz& a) {
return (a.a == 2 && a.b == 3);
}

int main() {
xyz begin[] = { {1, 2}, {2, 3}, {2, 3}, {3, 5} };
xyz* end = begin + 4;

// Forward find
xyz* found = std::find_if(begin, end, findit);
if (found != end)
std::cout << "Found at position "
<< found - begin
<< std::endl;

// Reverse find
found = std::find_if(std::reverse_iterator<xyz*>(end),
std::reverse_iterator<xyz*>(begin),
findit);
if (found != std::reverse_iterator<xyz*>(end));
std::cout << "Found at position "
<< found - std::reverse_iterator<xyz*>(end)
<< std::endl;

return 0;
}

还有 compiler error on codepad.org

最佳答案

std::find_if函数的返回类型等于作为参数传入的迭代器的类型。在你的情况下,因为你传递了 std::reverse_iterator<xyz*> s 作为参数,返回类型将为 std::reverse_iterator<xyz*> .这意味着

found = std::find_if(std::reverse_iterator<xyz*>(end),
std::reverse_iterator<xyz*>(begin),
findit);

不会编译,因为found是一个 xyz* .

要解决这个问题,你可以试试这个:

std::reverse_iterator<xyz*>
rfound = std::find_if(std::reverse_iterator<xyz*>(end),
std::reverse_iterator<xyz*>(begin),
findit);

这将修复编译器错误。但是,我认为您在这一行中有两个次要错误:

if (found != std::reverse_iterator<xyz*>(end));

首先,请注意 if 后面有一个分号语句,所以 if 的正文无论条件是否为真,语句都将被评估。

其次,注意 std::find_if如果 nothing 与谓词匹配,则返回第二个迭代器作为哨兵。因此,这个测试应该是

if (rfound != std::reverse_iterator<xyz*>(begin))

因为find_if将返回 std::reverse_iterator<xyz*>(begin)如果未找到该元素。

希望这对您有所帮助!

关于c++ - 如何在 C 风格数组上使用 find_if 和 reverse_iterator?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17201522/

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