我试图遍历一个列表,根据共享索引的另一个列表的值更新每个元素。
理想情况下,我希望使用这样的for-range循环来完成这个任务:
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试了一下,结果没什么好运气。
发布于 2015-06-18 12:30:55
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的引用,因此不会编译。正如你所期望的那样。
https://stackoverflow.com/questions/30915215
复制相似问题