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

标签 c++

我已经说过以下 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/

相关文章:

c++ - 两个智能指针之间的引用

c++ - 从指针 vector 中删除元素

c++ - C++中的赋值运算符模板和复制构造函数

返回后的 C++ 内存释放

c++ - ffmpeg:如何用 sws_scale() 替换 img_convert()

c++ - 在 C++ 中快速解析制表符分隔的字符串和整数

c++ - htmlcxx0.84编译错误

c++ - AOSP - 错误 : undefined reference to <function-name> during build

c++ - C++ 中的 vector 大小

c++ - 用于获取 netstat -s 统计信息的 Windows API