STL容器移动所选元素

use*_*rbb -2 c++ stl

如何从STL容器中选择具有特定值的元素并将其移动到该容器的末尾?

Bla*_*ace 5

您可以尝试使用std::partition返回不等于目标值的true元素的谓词.如果您需要保留元素的相对顺序,也有.std::stable_partition


Jim*_*som 5

考虑到你发表了关于想要使用std :: vector的评论,我建议使用std :: partition或std :: stable_partition,即:

#include <algorithm>
#include <functional>
#include <iostream>
#include <iterator>
#include <vector>

int main()
{
    int init_values[] = {1, 1, 7, 3, 19, 5, 5, 4, 5, 2, 5, 8, 9, 10, 5, 1};
    std::vector<int> values(
        init_values,
        init_values + sizeof(init_values) / sizeof(int)
    );

    std::stable_partition(
        values.begin(), values.end(),
        std::bind1st(std::not_equal_to<int>(), 5)
    );

    std::copy(values.begin(), values.end(), std::ostream_iterator<int>(std::cout, ", "));
    std::cout << "\n";

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

此代码将向量的所有元素移动到向量的末尾,保持其余元素的相对顺序.