STL容器移动选定的元素

STL Container move selected elements

本文关键字:元素 移动 STL      更新时间:2023-10-16

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

考虑到您对想要使用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;
}

此代码将把向量中等于5的所有元素移动到向量的末尾,保持其余元素的相对顺序。

您可以尝试将std::partition与谓词一起使用,该谓词为不等于目标值的元素返回true。如果需要保留元素的相对顺序,则还有std::stable_partition