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

标签 c++

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

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/

相关文章:

c++ - 设置背景颜色 CMDIFrameWnd

c++ - 为什么将 set::iterator 而不是 const_iterator 传递给函数会违反单一定义规则?

c++ - 我的Qt程序可以编译,但是在声明中使用ifstream时崩溃

c++ -//C++ 中的注释与 C 中的/* */

c++ - 在 C++ 中创建对象的函数

c# - 将 C++ 转换为 C#

c++ - 如何在 C++ 中将密码通过管道传递给 ssh?

FA 中的 C++ "call of overloaded is ambiguous"

c++ - 函数中的自动参数类型

Java 传值和类对象的 C++ 指针调用效果一样吗?