如何在给定的起始位置之前找到容器中的元素

How to find an element in a container before a given starting position?

本文关键字:元素 位置      更新时间:2023-10-16

我想找到容器中某个给定起始位置之前元素最后一次出现的

例如,如果我试图在字符串的s中找到给定字符之前的最后一个空格,我相信显而易见的方法是:

string::const_iterator b;
b = i; // <-- 'i' specifies where to start looking
while ((b != s.begin()) && (b[-1] != ' '))
    b--;

使用STL算法有更好的方法吗?


我试过:

b = find(string::const_reverse_iterator(i),
string::const_reverse_iterator(s.begin()), " ").base();

但我不确定这是否如预期的那样有效。

您可以使用std::string::find_last_of并指定它应该搜索的位置。下面将找到单词测试前第一个空格的位置。

#include <iostream>
#include <string>
int main()
{
    std::string foo = "this is a test string";
    auto pos = foo.find_last_of(" ", foo.find("test", 0));
    std::cout << pos;
    std::cin.get();
    return 0;
}

输出:

9

出于通用目的,我认为我会使用std::find_end和一个适当的lambda函数。页面上的示例很好地说明了函数的行为。

反向迭代器解决方案将起作用:

#include <iostream>
#include <algorithm>
int main()
{
    using std::string;
    using const_iterator = string::const_iterator;
    using const_reverse_iterator = string::const_reverse_iterator;
    string s("This is an sample");
    const_iterator pos = s.begin() + s.find("sample");
    const_reverse_iterator result = std::find(const_reverse_iterator(pos), s.crend(), 's');
    std::cout << string(s.cbegin(), result.base()) << 'n';
}

不过,您可能更喜欢@NathanOliver的解决方案。