如何在 std::vector 中找到<bool>哪些索引是真的?

How to find indices in an std::vector<bool> which are true?

本文关键字:gt 索引 真的 bool vector lt std      更新时间:2023-10-16

我说了以下布尔向量

v = [false ,true, false ,false ,true, false ,false ,true]

我想要另一个向量,它包含元素为真的 v 索引。

我有以下代码:

std::vector<int> nds; //contains the indices
for (const auto &elem : v)
{
auto idx = &elem - &v[0];
if (elem)
{
nds.push_back(idx);
}
}

上述内容似乎适用于我的MacBook,但在Linux上会导致以下错误。

src/file.cpp:76:25: error: taking address of temporary [-fpermissive]
auto idx = &elem - &v[0];
^

有没有更好的方法来查找索引?

附言这只是一些较大代码的片段。

有没有更好的方法来查找索引?

使用经典的 for 循环

for (int i = 0; i != v.size(); ++i) {
if (v[i]) nds.push_back(i);
}

使用 range-v3 库,可以使用函数式编程风格的方法将惰性views::enumerate迭代器与惰性views::filter链接起来,并views::transform视图转换来构造true值(原始(索引的std::vector<int>

const auto nds = v | views::enumerate 
| views::filter([](auto p) { return p.second; }) 
| views::transform([](auto p) { return p.first; }) 
| to<std::vector<int>>;

演示


或者,将views::transform替换为views::keys

const auto nds = v | views::enumerate 
| views::filter([](auto p){ return p.second; })
| views::keys
| to<std::vector<int>>;

演示