In C ++, instead of having one Iterable
, we pass an iterator (almost a pointer) to the beginning and end of the range:
template<typename Iter> std::string join(const std::string &sep, Iter begin, Iter end);
Please note that sep
must be passed as a reference to a constant, since you do not need to copy it.
You do not need to worry about whether the Iter
actually an iterator. This is because the code simply does not compile if it does not work.
For example, suppose you implemented it like this (this is a bad implementation):
template<typename Iter> std::string join(const std::string &sep, Iter begin, Iter end) { std::string result; while (begin != end) { result += *begin; ++begin; if (begin != end) result += sep; } return result; }
Then the type passed as Iter
should have operator++
, operator!=
And operator*
, which is a well-understood iterator contract.
source share