gpt4 book ai didi

c++ - 如何同时检查多个索引的 `std::vector` 是否为真?

转载 作者:行者123 更新时间:2023-12-02 15:47:03 24 4
gpt4 key购买 nike

我有一个 std::vector<bool>尺寸 N 和一个 std::vector<std::size_t>大小可变,包含 [0, N) 中的索引.检查第一个 vector 在第二个 vector 给出的所有索引处是否为真的惯用方法是什么?

我可能天真的解决方案是:

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;
}

最佳答案

一个惯用(虽然不一定有效)方法是使用std::all_of STL function ,使用一个谓词,该谓词仅返回 size_t vector 中每个值指定的索引处的 boolean vector 值。

这是一个大纲/演示:

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

bool all_true(const std::vector<bool>& data, const std::vector<size_t>& test)
{
return std::all_of(test.begin(), test.end(), [&data](size_t n) { return data[n]; });
}

int main()
{
std::vector<bool> bools{ true, true, true, true, false, false, true, false, true, false };
std::vector<size_t> test1{ 0, 1, 2, 3, 6, 8 }; // all true
std::vector<size_t> test2{ 0, 1, 2, 4, 7, 9 }; // some false

std::cout << "Test1: " << all_true(bools, test1) << "\n";
std::cout << "Test2: " << all_true(bools, test2) << "\n\n";

// Just to show that the order doesn't matter ...
std::cout << "After shuffling ...\n";
std::random_device rdev;
std::mt19937 rgen(rdev());
std::shuffle(test1.begin(), test1.end(), rgen);
std::shuffle(test2.begin(), test2.end(), rgen);
std::cout << "Test1: " << all_true(bools, test1) << "\n";
std::cout << "Test2: " << all_true(bools, test2) << "\n";

return 0;
}

关于c++ - 如何同时检查多个索引的 `std::vector<bool>` 是否为真?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73802668/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com