gpt4 book ai didi

c++ - 为什么我不能在 `ranges::begin` 上调用 `const filter_view` ?

转载 作者:行者123 更新时间:2023-12-04 13:53:43 24 4
gpt4 key购买 nike

我打不通 ranges::beginconst filter_view https://en.cppreference.com/w/cpp/ranges/filter_viewbeginend似乎不是 const .这是为什么?

int main(){
std::vector v{1,2,3};
// removing const will make it compile
const auto r = v | ranges::views::filter ([](auto&&){return true;});
ranges::begin(r);
}
https://godbolt.org/z/4feaYc

最佳答案

std::range中的所有观点图书馆在设计上很懒惰。在实践中意味着什么?这意味着在幕后,他们通常在 begin 上做得更多。 , end和迭代器操作比常规容器。通常为了能够保持这种懒惰,需要一些内部状态。例如,过滤 View 可以将迭代器存储到最后一个匹配元素或沿着这些行的东西。在这种情况下 begin()改变这个内部字段。甚至 cppreference 也说到了开始:

Returns the iterator initialized with {*this, ranges::find_if(base_, std::ref(*pred_))}. In order to provide the amortized constant time complexity required by the range concept, this function caches the result within the filter_view object for use on subsequent calls.


所以这是完全合理的 - 因为可以(并且很可能是)一个内部状态 begin()和/或 end()可以修改不能制作 const .

关于c++ - 为什么我不能在 `ranges::begin` 上调用 `const filter_view` ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66366084/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com