我正在尝试遍历一个列表,根据共享索引的另一个列表的值更新每个元素。
理想情况下,我想使用如下所示的 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
的引用,所以这不会编译。如您所料。