Reputation: 3482
I see a lot of people resolve to signed int
, but it seems to me like that is out of ignorance, because that causes signed/unsigned mismatches for container types who use unsigned size_type
s.
Since there is no way to get the type of container for the provided iterators, I do not see a way to get the size_type
of the assumed container to perform accurate arithmetic.
What type should we use when performing arithmetic operations on Iterators? Or even better yet, how could one get the underlying size_type
of the container since iterators have no knowledge of their parent container?
Edit2:
What I mean by the underlying size type would be, for example:
std::vector<some_type>::size_type
for some iterator whose container type is std::vector<some_type>
Edit1:
I think C++17 is providing a solution to this problem via some container access functions:
These non-member functions provide a generic interface for containers, plain arrays, and std::initializer_list.
More specifically size gives the declared type of the size field for the parent container.
Upvotes: 1
Views: 597
Reputation:
My recommendation is to use std::iterator_traits<It>::difference_type
(It
is iterator type), which is typically (but not mandated to be) std::ptrdiff_t
. std::ptrdiff_t
is an alias of a signed type.
I recommend this because of the following facts:
std::distance
returns std::iterator_traits<It>::difference_type
.std::next
and std::prev
takes std::iterator_traits<It>::difference_type
as parameter.Upvotes: 4