如何在C风格的数组上使用find_if和reverse_iterator?

时间:2013-06-19 21:17:06

标签: c++ arrays iterator reverse-iterator

要使用POD元素搜索C-Array中元素的第一个出现位置,可以使用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);

这给了我错误:

  

无法转换'std :: reverse_iterator&lt; xyz *&gt;分配给'xyz *'

您是否知道如何以这种方式进行操作,或者您是否知道更好的解决方案?

这是代码:

#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

1 个答案:

答案 0 :(得分:12)

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

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

无法编译,因为foundxyz*

要解决此问题,您可以尝试:

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如果没有与谓词匹配,则将第二个迭代器作为标记返回。因此,这个测试应该是

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

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

希望这有帮助!

相关问题