Foxy
Foxy

Reputation: 1109

use std::stable_partition and ::iterator with a vector

I'm trying to organize a vector that could contain this:

[0]:  "people:"
[1]:  "James"
[2]:  "Jhones"
[3]:  "unknown person"
[4]:  "Mary"
[5]:  "Bob"
[6]:  "unknown person"
[7]:  "hobbies:"
[8]:  "Baseball"
[9]:  "unknown hobbies"
[10]: "Ping-pong"
[11]: "FootBall"
[12]: "unknown hobbies"
...

In order to organize the information, I would like each string beginning with the term "unknown" to be "go up" just below the last value ending with ":"

Which would give me:

[0]:  "people:"
[1]:  "unknown person"
[2]:  "unknown person"
[3]:  "James"
[4]:  "Jhones"
[5]:  "Mary"
[6]:  "Bob"
[7]:  "hobbies:"
[8]:  "unknown hobbies"
[9]:  "unknown hobbies"
[10]: "Baseball"
[11]: "Ping-pong"
[12]: "FootBall"
...

To do this, I have decided to use std::stable_partition. This is my function:

std::vector<std::string> Organize(std::vector<std::string> vec) {
    using namespace std;
    auto it = find_if(vec.rbegin(), vec.rend(), [](auto a) {return a.back() == ':'; });
    stable_partition(it.base(), vec.end(), [](string s) {return s_startswith(s, "unknown"); });
    for (string str : vec)
        cout << " --> " << str << endl;
    return vec;
}

voici ma fonction s_startswith :

bool s_startswith(std::string const &str, std::string const &fnd) {
    return (str.rfind(fnd, 0) == 0);
}

I thought it might have worked, but I have this error message displayed:

I think I understand what causes the error, but I don't know how to correct it...

Don't worry if this "organization" doesn't make sense. It is perfect, but I have made it much simpler in order to see the essential.

Could you help me, please?

Upvotes: 0

Views: 159

Answers (1)

3CxEZiVlQ
3CxEZiVlQ

Reputation: 38773

I suppose the problem is in the lamda. The string a is empty. Access a.back() is invalid.

auto it = find_if(vec.rbegin(), vec.rend(), [](auto a) {return a.back() == ':'; });

Make sure all vector elements are not empty.

Upvotes: 1

Related Questions