[英]In C++, how do I create a function that accepts an InputIterator?
C++ transform
, accumulate
, and similar functions accept an InputIterator
as an argument, so they can be used with many types of containers. C ++ transform
, accumulate
和类似函数接受InputIterator
作为参数,因此它们可以与许多类型的容器一起使用。 I want to write a function that accepts InputIterator
so I can use the function with any type of container. 我想编写一个接受InputIterator
的函数,以便可以将该函数与任何类型的容器一起使用。 How do I do that? 我怎么做? What headers do I need, etc. 我需要什么标题,等等。
You don't need any headers. 您不需要任何标题。 You just make a function template, and document your template to require an argument that is an input iterator. 您只需制作一个功能模板,并记录您的模板以要求使用作为输入迭代器的参数。 You may like to use the iterator_traits
template from the <iterator>
header to extract adherent data, though. 但是,您可能想使用<iterator>
头中的iterator_traits
模板来提取粘附数据。 For example: 例如:
#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;
}
For some algorithms you don't need traits at all, and therefore no headers. 对于某些算法,您根本不需要特征,因此不需要标题。 For example: 例如:
// 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;
}
InputIterator
is a concept more than a type. InputIterator
一个概念,更是一种概念。
Just write 写吧
template<typename InputIterator>
void myFunc(InputIterator begin, InputIterator end) {
/* … */
}
and you are good to go, if you apply on the begin
and end
variables only actions that correspond to the InputIterator
concept (incrementation, dereference…). 如果您将begin
和end
变量仅应用到与InputIterator
概念相对应的InputIterator
(增量,取消引用…),那么您就很好了。
I'd suspect you already did have a look at eg std::transform()
documentation yet. 我怀疑您已经看过例如std::transform()
文档了。
You should have noticed that they're taking these iterator types as template parameters: 您应该已经注意到,他们将这些迭代器类型用作模板参数:
template< class InputIt, class OutputIt, class UnaryOperation >
OutputIt transform( InputIt first1, InputIt last1, OutputIt d_first,
UnaryOperation unary_op );
The particular requirements are checked at compile time, using the various concepts defined in the standard language, and being defined as eg std::iterator_traits<It>
. 特定要求在编译时使用标准语言中定义的各种概念进行检查,并定义为例如std::iterator_traits<It>
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.