435,285 Members | 2,124 Online
Need help? Post your question and get tips & solutions from a community of 435,285 IT Pros & Developers. It's quick & easy.

# How to calculate size() from iterators

 P: n/a Hi all, How can I compute the size of vector given iterators to it. Can I do : int size = itEnd - itBegin; ??? Cheers, Paulo Matos Jul 23 '05 #1
4 Replies

 P: n/a pmatos wrote: How can I compute the size of vector 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 Jul 23 '05 #2

 P: n/a On 2005-06-14 12:11:17 -0400, "pmatos" said: Hi all, How can I compute the size of vector 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. -- Clark S. Cox, III cl*******@gmail.com Jul 23 '05 #3

 P: n/a Clark S. Cox III wrote: On 2005-06-14 12:11:17 -0400, "pmatos" said: Hi all, How can I compute the size of vector 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) 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? ...as this will work with other iterator categories as well. -- Clark S. Cox, III cl*******@gmail.com Jul 23 '05 #4

 P: n/a pmatos wrote: 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. -- Pete Becker Dinkumware, Ltd. (http://www.dinkumware.com) Jul 23 '05 #5

### This discussion thread is closed

Replies have been disabled for this discussion.