c++ - 在 C++ 中,如何创建接受 InputIterator 的函数?

标签 c++ c++11

C++ transformaccumulate 和类似函数接受一个 InputIterator 作为参数,因此它们可以用于多种类型的容器。我想编写一个接受 InputIterator 的函数,这样我就可以将该函数用于任何类型的容器。我怎么做?我需要什么 header 等。

最佳答案

您不需要任何 header 。您只需制作一个函数模板,并记录您的模板以需要一个作为输入迭代器的参数。您可能喜欢使用 iterator_traits来自 <iterator> 的模板 header 提取附着数据,虽然。例如:

#include <iterator>

//  Requires: InputIterator is an input iterator
//  Returns: sum of the range, starting at acc

template <typename InputIterator>
typename std::iterator_traits<InputIterator>::value_type
sum(InputIterator it,
    InputIterator last,
    typename std::iterator_traits<InputIterator>::value_type acc)
{
    while (it != last) { acc += *it; ++it; }
    return acc;
}

对于某些算法,您根本不需要特征,因此不需要 header 。例如:

// Requires: Iter is an input iterator, F is a callable and copyable
// Returns: a copy of f
// Effects: calls f with every value in the range
template <typename Iter, typename F>
F for_each(Iter it, Iter last, F f)
{
    while (it != last) { f(*it); ++it; }
    return f;
}

关于c++ - 在 C++ 中,如何创建接受 InputIterator 的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30968955/

相关文章:

c++ - 如果未定义 move 语义( move 构造函数和 move 赋值运算符),编译器是否默认优化?

c++ - 我该怎么办 : convert surface to a texture or create a texture with certain multisampling parameters or render a surface with an alpha layer

C++ Function Hook(仅内存地址)

c++ - 如何编写常量函数引用

c++ - 为什么在以下情况下不需要对依赖类型使用 typename ?

c++ - 为什么 gcc 4.9 (trunk) 这么慢?

c++ - 在C++中围绕另一个圆在圆形路径中制作圆轨道

c++ - 如何清理(用随机字节覆盖)std::string 内部缓冲区?

c++ - 跨应用共享文件

c++ - 防止对 std::unique_ptr 的不安全取消引用