gpt4 book ai didi

c++ - 如何在C++中通过函数序列创建输入迭代器?

转载 作者:行者123 更新时间:2023-12-02 10:32:35 28 4
gpt4 key购买 nike

我有一个函数,可以获取一对输入迭代器:

template<typename I>
void foo(I begin, I end) {...}

我想用函数生成的序列(例如随机数序列)来填充它。
是否有任何标准的库机制来实现此目的,而无需将序列存储在集合中,然后从集合中获取迭代器?

最佳答案

您将需要自己构建。这是一个如何做的例子:

template<typename F>
class function_iterator {
using function = F;
public:
using value_type = std::invoke_result_t<function>;
using difference_type = std::ptrdiff_t;
using reference = value_type const&;
using pointer = value_type const*;
using iterator_category = std::input_iterator_tag;

function_iterator(function f, difference_type pos = 0);

auto operator*() const -> value_type;
auto operator++() -> function_iterator&;
auto operator++(int) -> function_iterator;

private:
function f_;
difference_type pos_;

template<typename T_>
friend bool operator==(function_iterator<T_> const& lhs, function_iterator<T_> const& rhs);
template<typename T_>
friend bool operator!=(function_iterator<T_> const& lhs, function_iterator<T_> const& rhs);
};

template<typename T>
function_iterator<T>::function_iterator(function f, difference_type pos) :
f_(f), pos_(pos) {
}

template<typename F>
auto function_iterator<F>::operator*() const -> value_type {
return f_();
}
template<typename F>
auto function_iterator<F>::operator++() -> function_iterator& {
++pos_;
return *this;
}
template<typename F>
auto function_iterator<F>::operator++(int) -> function_iterator {
auto it = *this;
++*this;
return it;
}

template<typename T_>
bool operator==(function_iterator<T_> const& lhs, function_iterator<T_> const& rhs) {
return lhs.pos_ == rhs.pos_;
}
template<typename T_>
bool operator!=(function_iterator<T_> const& lhs, function_iterator<T_> const& rhs) {
return !(lhs == rhs);
}

Live

关于c++ - 如何在C++中通过函数序列创建输入迭代器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61704524/

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