我可以以非常量的方式使用 Boost.Range 索引适配器吗?
Can I use the Boost.Range indexed adaptor in a non-const way?
我正在尝试遍历一个列表,根据共享索引的另一个列表的值更新每个元素。
理想情况下,我想使用如下所示的 for 范围循环来做到这一点:
std::vector<int> is;
std::vector<int> other_list;
for (auto &i : is | boost::adaptors::indexed(0)) {
i.value() = other_list[i.index()];
}
但是我收到这样的错误:
indexed.cpp:29:48: error: invalid initialisation of non-const reference of type 'boost::range::index_value<int&, long int>&' from an rvalue of type 'boost::iterator_facade<boost::range_detail::indexed_iterator<__gne_cxx::__normal_iterator<int*, std::vector<int> > >, boost::range::index_value<int&, long int>, boost::random_access_traversal_tag, boost::range::index_value<int&, long in>, long int>::reference {aka boost::range::index_value<int&, long int>}'
我所追求的 Boost.Range 是不可能的,还是我只是做错了?
NB:我也尝试过,boost::combine
不再有运气。
indexed
有点有趣,因为它给你一个范围,谁的元素有一个value()
和一个index()
,而不是它们本身是值。关键是你实际上不需要通过引用来获取indexed
元素 - 因为value()
本身是可修改的。
例如,如果我要更改 Boost 提供的示例:
int main(int argc, const char* argv[])
{
using namespace boost::assign;
using namespace boost::adaptors;
std::vector<int> input = {10, 20, 30, 40, 50};
for (const auto& element : input | indexed(0))
{
element.value() = 1;
}
for (int i : input) {
std::cout << i << ' ';
}
return 0;
}
element
可能是对 const 的引用,但我仍然可以更改所有值。
但是,如果input
是一个const
范围 - 那么value()
本身就是对const
的引用,所以这不会编译。如您所料。
相关文章:
- 数组索引的值没有增加
- 芬威克树(BIT).找到具有给定累积频率的最小索引,单位为 O(logN)
- 查找最接近的大于当前数字的数字的索引
- 在C++中调整向量中的索引
- 重载元组索引运算符-C++
- 给定一个向量,如何找到该向量的所有子集和的原始索引
- 为std::string的某个索引赋值
- 并行用于C++17中数组索引范围内的循环
- 跟随整数索引列表的自定义类迭代器
- 如何在for循环中包含两个索引值的测试条件
- D3D11-将混合权重和索引传递到顶点着色器
- 将转换字符键入 int 以用作向量C++的索引
- 在 C++ 中访问数组负索引处的内存不会返回垃圾
- 如何为圆环创建索引
- 在子集化后将包含索引号的列表列表映射到标准索引序列
- 查找字符在两个索引之间出现的次数
- Azure Kinect 使用正文索引映射裁剪正文
- 如何查找哪个类对象位于数组的特定索引上(多态性)
- 从整数索引的for循环枚举到range-for
- 我可以以非常量的方式使用 Boost.Range 索引适配器吗?