JLagana
JLagana

Reputation: 1294

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

I would like to find the last occurrence of an element in a container before some given starting position.

For instance, if I'm trying to find the last space before a given character in a string 's', I believe the obvious approach would be something like:

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

Is there a better way to do this using STL algorithms?


I've tried:

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

But I'm not sure if this works as intended.

Upvotes: 2

Views: 167

Answers (3)

sergiol
sergiol

Reputation: 4335

For generic purposes, I think I would use std::find_end with an adequate lambda function. The example on the page illustrates well the function's behavior.

Upvotes: 1

user2249683
user2249683

Reputation:

The reverse iterator solution will work:

#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';
}

However, you might prefer the solution of @NathanOliver.

Upvotes: 0

NathanOliver
NathanOliver

Reputation: 181057

You can use std::string::find_last_of and specify where it should search no farther than. The following will find the position of the first space before the word test.

#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;
}

Output:

9

Upvotes: 2

Related Questions