我已经说过以下 bool vector v = [false ,true, false ,false ,true, false ,false ,true]
我想要另一个 vector ,其中包含元素为真的 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];
^
有没有更好的方法来找到索引?附言这只是一些较大代码的片段。
最佳答案
is there a better way to find the indices?
使用经典的 for 循环
for (int i = 0; i != v.size(); ++i) {
if (v[i]) nds.push_back(i);
}
关于c++ - 如何在 std::vector<bool> 中找到正确的索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62673997/