如何在 std::vector 中找到<bool>哪些索引是真的?
How to find indices in an std::vector<bool> which are true?
我说了以下布尔向量
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>>;
演示。
相关文章:
- 数组索引的值没有增加
- 芬威克树(BIT).找到具有给定累积频率的最小索引,单位为 O(logN)
- 查找最接近的大于当前数字的数字的索引
- 在C++中调整向量中的索引
- 重载元组索引运算符-C++
- 给定一个向量,如何找到该向量的所有子集和的原始索引
- 为std::string的某个索引赋值
- 并行用于C++17中数组索引范围内的循环
- EASTL矢量<向量<int>>连续的
- 跟随整数索引列表的自定义类迭代器
- 如何在for循环中包含两个索引值的测试条件
- D3D11-将混合权重和索引传递到顶点着色器
- 将转换字符键入 int 以用作向量C++的索引
- 在 C++ 中访问数组负索引处的内存不会返回垃圾
- 如何为圆环创建索引
- 在子集化后将包含索引号的列表列表映射到标准索引序列
- 查找字符在两个索引之间出现的次数
- Azure Kinect 使用正文索引映射裁剪正文
- 如何查找哪个类对象位于数组的特定索引上(多态性)
- 数组索引重载错误