如何在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
相关产品推荐
相关产品推荐

