How to calculate size() from iterators

P

pmatos

Hi all,

How can I compute the size of vector<int> given iterators to it. Can I
do :
int size = itEnd - itBegin;
???

Cheers,

Paulo Matos
 
V

Victor Bazarov

pmatos said:
How can I compute the size of vector<int> given iterators to it. Can I
do :
int size = itEnd - itBegin;
???

You can, but only for the containers whose iterators are random-access
ones. Other iterators cannot be subtracted from each other.

V
 
C

Clark S. Cox III

Hi all,

How can I compute the size of vector<int> given iterators to it. Can I
do :
int size = itEnd - itBegin; ???

In the case of vector, yes, you can do that. This is because vector's
iterators are "Random Access" iterators. If you want to be able to work
with other kinds of iterators, then use:

size = std::distance(itBegin, itEnd)

....as this will work with other iterator categories as well.
 
P

pmatos

Clark said:
In the case of vector, yes, you can do that. This is because vector's
iterators are "Random Access" iterators. If you want to be able to work
with other kinds of iterators, then use:

size = std::distance(itBegin, itEnd)

Probably, for portability, flexibility and maintenance I should be
using this always since it will always work and the compiler will most
probably optimize it to itEnd - itBegin in the case of random access
containers. Right?
 
P

Pete Becker

pmatos said:
Probably, for portability, flexibility and maintenance I should be
using this always since it will always work and the compiler will most
probably optimize it to itEnd - itBegin in the case of random access
containers. Right?

It's not a matter of portability. vector iterators are always random
access, so you can always subtract them. If you think you might change
from a vector to some other container that doesn't provide random access
iterators then distance might be the appopriate choice, if it isn't too
slow.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,534
Members
45,008
Latest member
Rahul737

Latest Threads

Top