如何在 std::vector<bool> 中找到正确的索引?

Mor*_*eus 3 c++

我已经说过以下布尔向量

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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

src/file.cpp:76:25: error: taking address of temporary [-fpermissive]
                         auto idx = &elem - &v[0];
                                                ^
Run Code Online (Sandbox Code Playgroud)

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

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

And*_* DM 8

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

使用经典的 for 循环

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