Questions on Vectors

Nov 26, 2014 at 2:24pm
I had two questions regarding vectors:
1) Is there any advantage to using iterators instead of [] like arrays?

2) What is the need for having two types of iterators - iterator and reverse iterator?
Last edited on Nov 26, 2014 at 2:26pm
Nov 26, 2014 at 2:45pm
1) Is there any advantage to using iterators instead of [] like arrays?
Same advantage as using pointers for arrays. You can pass iterator arount without need for passing both container and index. Allows your functions to work even for containers which does not support random access.

2) What is the need for having two types of iterators - iterator and reverse iterator? Reverse iterator allows using same functions to iterate range forward and backward:
1
2
std::find(vec. begin(), vec. end(), some_value); //Finds FIRST entry of some_value
std::find(vec.rbegin(), vec.rend(), some_value); //Finds LAST entry of some_value 
Nov 26, 2014 at 3:22pm
1)Oh. That clears it up!

2)
allows using same functions to iterate range forward and backward:
1
2
std::find(vec. begin(), vec. end(), some_value); //Finds FIRST entry of some_value
std::find(vec.rbegin(), vec.rend(), some_value); //Finds LAST entry of some_value  


But why not use:
std::find(vec.end(), vec.back(), some_value);
Nov 26, 2014 at 3:48pm
Because find() iterates forward. And as there is no elements after end() (and end() is not pointing tovalid element anyway) you will be luchky if it will just crash.
Nov 27, 2014 at 4:05am
Okay. That makes sense.
Thanks a lot!
Topic archived. No new replies allowed.