Reputation: 1527
I try to build a template function that gets 2 iterators(begin
and end
) of either a vector
or an array
(this must be unknown container passed to function).
I want that the function will check for the size of the container passed to it.
My problems are: if begin iterator
equals end iterator
does it mean 0 or 1 elements inside container?
How can I decalare some universal size type ?
If I want to sort the unknown container by passing iterators to sort function is that becomes a problem? I have some feeling that it won't work.
This is my draft of the template function:
template<class P, class T>
T my_func(P beg, P end)
{
typedef typename ??? container_size;
if (beg == end)//first problem to determine if contains 0 or 1
elements
throw domain_error("some message if 0 elements");
sort(beg, end);// scond problem
}
Upvotes: 2
Views: 214
Reputation: 21576
- I want that the function will check for the size of the container passed to it. My problems are: if begin iterator equals end iterator does it mean 0 or 1 elements inside container? How can I decalare some universal size type ?
You should use std::distance
for that.
- If I want to sort the unknown container by passing iterators to sort function is that becomes a problem? I have some feeling that it won't work.
It would work, provided the iterators are RandomAccessIterators and the value type is swappable
So, your code could be:
template<class P, class T>
T my_func(P first, P last)
{
if(first == last) // No elements within the range
throw domain_error("some message if 0 elements");
//Number of Elements within the range
auto container_size = std::distance(first, last);
std::sort(first, last);
return ...;
}
If my guess is correct, that the template parameter T
is supposed to be the value type of the iterator, you can obtain it using std::iterator_traits<T>::value_type
Upvotes: 8