C++ 标准库 copy_if

在 C++ 中,有多种方法可以从一个容器拷贝符合条件的元素到另一个容器。以下是几种常用的方法:

1. 使用 std::copy_if 算法(推荐)

这是最简洁和现代的方法:

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

int main() {
    std::vector<int> source = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    std::vector<int> destination;
    
    // 拷贝所有偶数
    std::copy_if(source.begin(), source.end(), 
                 std::back_inserter(destination),
                 [](int x) { return x % 2 == 0; });
    
    // 输出结果
    for (int num : destination) {
        std::cout << num << " ";
    }
    // 输出: 2 4 6 8 10
    
    return 0;
}

2. 使用 std::remove_copy_if(拷贝不满足条件的元素)

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

int main() {
    std::vector<int> source = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    std::vector<int> destination;
    
    // 拷贝所有不是偶数的元素(即奇数)
    std::remove_copy_if(source.begin(), source.end(),
                       std::back_inserter(destination),
                       [](int x) { return x % 2 == 0; });
    
    // 输出结果
    for (int num : destination) {
        std::cout << num << " ";
    }
    // 输出: 1 3 5 7 9
    
    return 0;
}

3. 对于关联容器(如 std::set, std::map)

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

int main() {
    std::set<int> source = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    std::vector<int> destination;
    
    // 从 set 拷贝大于 5 的元素到 vector
    std::copy_if(source.begin(), source.end(),
                 std::back_inserter(destination),
                 [](int x) { return x > 5; });
    
    for (int num : destination) {
        std::cout << num << " ";
    }
    // 输出: 6 7 8 9 10
    
    return 0;
}

4. 性能考虑

如果知道大概有多少元素会被拷贝,可以预先分配空间:

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

int main() {
    std::vector<int> source = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    
    // 预先分配空间(可选,用于性能优化)
    std::vector<int> destination;
    destination.reserve(source.size()); // 最大可能的大小
    
    std::copy_if(source.begin(), source.end(),
                 std::back_inserter(destination),
                 [](int x) { return x % 2 == 0; });
    
    // 可以收缩空间以节省内存
    destination.shrink_to_fit();
    
    for (int num : destination) {
        std::cout << num << " ";
    }
    
    return 0;
}

总结

  • 推荐使用 std::copy_if:代码简洁,表达意图明确
  • 使用 std::back_inserter 作为输出迭代器,自动处理容器大小
  • 考虑性能:对于大型容器,可以预先分配空间
  • lambda 表达式:提供了灵活的条件判断方式

选择哪种方法取决于具体需求和个人偏好,但 std::copy_if 通常是首选,因为它提供了最好的可读性和简洁性。



note: from deepseek.
posted @ 2025-09-10 13:44  double64  阅读(15)  评论(0)    收藏  举报