You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C++中实现类似Python的布尔索引选择Vector元素?

C++中实现类似Numpy布尔数组选子集的方式

当然有,C++里可以通过多种方式实现和你示例中一样的布尔索引选子集功能,下面是几种常见方案:

1. 使用标准库std::copy_if(无需第三方库)

这是最通用的方式,依赖C++标准库的算法,适用于所有标准容器(比如std::vector):

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

int main() {
    std::vector<int> a = {1, 2, 3, 4, 5, 6};
    std::vector<bool> mask = {false, true, true, false, true, true};
    std::vector<int> b;

    // 遍历原数组,根据mask筛选元素
    std::copy_if(a.begin(), a.end(), std::back_inserter(b),
        [&mask, idx = 0](int val) mutable {
            return mask[idx++];
        });

    // 输出结果
    for (int num : b) {
        std::cout << num << " ";
    }
    // 输出:2 3 5 6
    return 0;
}

2. 手动遍历实现

如果不想用算法库,手动循环筛选更直观:

#include <vector>
#include <iostream>

int main() {
    std::vector<int> a = {1, 2, 3, 4, 5, 6};
    std::vector<bool> mask = {false, true, true, false, true, true};
    std::vector<int> b;

    for (size_t i = 0; i < a.size(); ++i) {
        if (mask[i]) {
            b.push_back(a[i]);
        }
    }

    for (int num : b) {
        std::cout << num << " ";
    }
    // 输出:2 3 5 6
    return 0;
}

3. 使用数值计算库(如Eigen)实现类Numpy语法

如果你的项目用到了数值计算库Eigen,它支持类似Numpy的布尔索引语法,写法更接近Python示例:

#include <Eigen/Dense>
#include <iostream>

int main() {
    Eigen::ArrayXi a = Eigen::ArrayXi::LinSpaced(6, 1, 6); // [1,2,3,4,5,6]
    Eigen::Array<bool, 6, 1> mask;
    mask << false, true, true, false, true, true;

    Eigen::ArrayXi b = a(mask); // 直接用布尔数组索引

    std::cout << b << std::endl;
    // 输出:
    // 2
    // 3
    // 5
    // 6
    return 0;
}

内容的提问来源于stack exchange,提问作者PhiloRobotist

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 22:06:34