如何使用C++标准库处理std::array中相邻1的合并统计?
如何使用C++标准库处理std::array中相邻1的合并统计?
这个需求挺清晰的,咱们完全可以用C++11的标准库工具来实现,不用手写复杂的原生循环。先明确核心逻辑:把数组里每一段连续的1替换成它们的总个数,把每个0替换成1,最后按原顺序输出这些转换后的值。
方法一:用std::for_each遍历处理
这是最直观的实现方式,通过遍历数组元素,维护一个计数器跟踪当前连续1的数量,遇到0时完成对应处理:
#include <array> #include <vector> #include <algorithm> #include <iostream> int main() { std::array<int, 8> arr = {0, 1, 1, 1, 0, 1, 1, 0}; std::vector<int> result; int count_ones = 0; // 用std::for_each遍历数组,lambda捕获结果容器和计数器 std::for_each(arr.begin(), arr.end(), [&](int num) { if (num == 1) { // 遇到1就累加计数 ++count_ones; } else { // 遇到0时,先处理之前累计的连续1(如果有的话) if (count_ones > 0) { result.push_back(count_ones); count_ones = 0; } // 把0转换为1加入结果 result.push_back(1); } }); // 处理数组末尾可能剩余的连续1(比如原数组以1结尾的情况) if (count_ones > 0) { result.push_back(count_ones); } // 验证输出结果 for (int num : result) { std::cout << num << " "; } // 输出:1 3 1 2 1 return 0; }
方法二:用std::accumulate聚合处理
如果你想更“函数式”一点,可以用std::accumulate来一次性完成结果的构建,它会把数组元素逐个聚合到一个状态对象里:
#include <array> #include <vector> #include <numeric> #include <iostream> int main() { std::array<int, 8> arr = {0, 1, 1, 1, 0, 1, 1, 0}; // 用std::accumulate,状态对象是pair:第一个元素是连续1的计数器,第二个是结果容器 std::pair<int, std::vector<int>> acc = std::accumulate( arr.begin(), arr.end(), std::make_pair(0, std::vector<int>{}), [](std::pair<int, std::vector<int>> acc_state, int num) { if (num == 1) { acc_state.first++; } else { if (acc_state.first > 0) { acc_state.second.push_back(acc_state.first); acc_state.first = 0; } acc_state.second.push_back(1); } return acc_state; } ); // 处理末尾剩余的连续1 if (acc.first > 0) { acc.second.push_back(acc.first); } // 验证输出 for (int num : acc.second) { std::cout << num << " "; } // 输出:1 3 1 2 1 return 0; }
这两种方法都完全依赖C++11标准库的特性(lambda表达式、std::for_each、std::accumulate),没有使用任何非标准扩展,完全符合你的要求。
备注:内容来源于stack exchange,提问作者markzzz
相关产品推荐
相关产品推荐

