C++ transform
, accumulate
, and similar functions accept an InputIterator
as an argument, so they can be used with many types of containers. I want to write a function that accepts InputIterator
so I can use the function with any type of container. 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. 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.
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…).
I'd suspect you already did have a look at eg std::transform()
documentation yet.
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>
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.