将std :: stable_partition和:: iterator与向量一起使用

时间:2018-03-10 14:18:33

标签: c++ vector

我试图组织一个可能包含此内容的向量:

[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"
...

为了整理信息,我希望每个字符串都以“" unknown"成为"上升"在"结束的最后一个值的下方:"

哪会给我:

[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"
...

为此,我决定使用std :: stable_partition。这是我的功能:

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 think I understand what causes the error, but I don't know how to correct it...

不要担心这个&#34;组织&#34;没有意义。它是完美的,但为了看到必要的东西,我已经简化了它。

请问你能帮帮我吗?

1 个答案:

答案 0 :(得分:1)

我想问题出现在lamda。字符串a为空。访问a.back()无效。

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

确保所有向量元素都不为空。