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

如何同时检查std::vector<bool>多个指定索引的值是否全为true?

问题

我有一个大小为N的std::vector<bool>,以及一个元素为[0, N)范围内索引、大小可变的std::vector<std::size_t>。请问有没有符合C++惯用风格的方法,检查第一个vector在第二个vector给出的所有索引处的值是否都为true?

我初步的解决方案如下:

auto all_true(
    std::vector<bool> const& bools, std::vector<std::size_t> const& indexes)
    -> bool {
  auto res = true;
  for (auto index : indexes) {
    res = res and bools[index];
  }
  return res;
}
符合C++惯用风格的实现

C++标准库<algorithm>头文件中的std::all_of算法就是最贴合惯用风格的方案,它专门用来判断范围内所有元素是否满足指定条件,代码简洁且语义直接。

基础实现

#include <algorithm> // 必须包含此头文件

auto all_true(std::vector<bool> const& bools, std::vector<std::size_t> const& indexes) -> bool {
    return std::all_of(indexes.begin(), indexes.end(), [&bools](std::size_t idx) {
        return bools[idx];
    });
}

关键说明

  • std::all_of会遍历indexes的每个元素,对每个索引执行lambda里的判断逻辑
  • 和你手动实现的逻辑一样,一旦遇到bools[idx]为false,算法会立即终止遍历,保留短路求值的效率
  • 代码语义清晰,直接表达了“所有索引对应的bool值都为true”的意图,符合C++社区的惯用写法

通用模板版本(可选)

如果需要支持更多类型的容器(比如std::array、std::list等),可以把函数模板化,提升复用性:

#include <algorithm>
#include <concepts>

template<std::ranges::input_range BoolRange, std::ranges::input_range IndexRange>
requires std::convertible_to<std::ranges::range_value_t<IndexRange>, std::size_t>
auto all_true(BoolRange const& bools, IndexRange const& indexes) -> bool {
    return std::ranges::all_of(indexes, [&bools](auto idx) {
        return bools[static_cast<std::size_t>(idx)];
    });
}

这个版本基于C++20的范围概念,支持所有符合输入范围要求的容器,同时确保索引可以安全转换为std::size_t类型。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 03:00:51