使用
auto empty_line = [](auto& str){ return str.size() == 0; };
我们做得到:
auto line_range_with_first_non_empty =
ranges::view::drop_while(ranges::getlines(std::cin),empty_line);
auto input1 = std::stoi(*line_range_with_first_non_empty.begin());
我们也可以这样做:
auto line_range2 = ranges::getlines(std::cin);
auto iter2 = ranges::find_if_not(line_range2,empty_line);
auto input2 = std::stoi(*iter2);
不幸的是,当我尝试将上面的版本缩短为:
auto iter3 = ranges::find_if_not(ranges::getlines(std::cin),empty_line);
// auto input3 = std::stoi(*iter3);
我收到一个错误:
<source>:22:29: error: indirection requires pointer operand ('ranges::v3::dangling<ranges::v3::_basic_iterator_::basic_iterator<ranges::v3::getlines_range::cursor> >' invalid)
auto input3 = std::stoi(*iter3);
^~~~~~
我以为是因为那个无限的范围,但我错了。
auto sin = std::istringstream{"\n\n\nmy line\n"};
auto iter4 = ranges::find_if_not(ranges::getlines(sin),empty_line);
// Error when deref.
// auto input4 = std::stoi(*iter4);
这会产生相同的错误。
<source>:27:29: error: indirection requires pointer operand ('ranges::v3::dangling<ranges::v3::_basic_iterator_::basic_iterator<ranges::v3::getlines_range::cursor> >' invalid)
auto input4 = std::stoi(*iter4);
^~~~~~
为什么我不能在ranges::find_if
将范围作为右值时取消引用?
是否ranges::getlines
返回范围?如果是这样,范围应该拥有东西吗?