C++ transform
、accumulate
和类似函数接受一个 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/