+ 1

c++ vector questions

What exactly is vector<int> :: iterator i Why the type? (<int>) Why can't we use a normal for loop to iterate through a vector? what's the difference between using that iterator, and using for(int i :: myvector) (I think that's how I remember it)? Iteration with vectors just seems odd, ya know?

8th Feb 2019, 6:25 AM
Daniel Cooper
Daniel Cooper - avatar
7 Réponses
+ 5
1) Simply is an object of type iterator. Note than exists 5 types of iterators divided in hierarchy. 2) Because C++ had to know which object is used by data structure for make checks and right allocations in code 3) Who say this? You can use use normal loop for looping on a vector 3) Its same, only than all is hided to you 4) I didnt understandood this question... I dont think that is strange the iteration on vector data structure...
8th Feb 2019, 8:13 AM
KrOW
KrOW - avatar
+ 5
You are welcome 👍👍👍 Remember to bookmarks the site for C++ reference 😉
8th Feb 2019, 6:44 PM
KrOW
KrOW - avatar
+ 3
vector is template class. When you use keyword : vector<MyClass>, at compile time compiler writes a new class for you. So that's why specifying type in <> is necessary. Iterators are objects which are like pointers in simple array. Iterators can be incremented/decremented using unary + / - and can be compared to other iterators using ==/!= . iterators can be dereferenced to get actual value. There are different STL functions which take iterators as parameters. We have begin and end method to get iterators for first and (last element + 1). end iterator cannot be dereferenced. You can do something like this :- for(auto i = myvec.begin(); i!= myvec.end(); i++) { cout << *i; } p.s. I read about iterators yesterday, correct me if I am wrong
8th Feb 2019, 6:46 AM
code learner
code learner - avatar
+ 3
I answer you in this way: read here http://www.cplusplus.com/reference/iterator/
8th Feb 2019, 4:27 PM
KrOW
KrOW - avatar
+ 1
KrOW So somebody on Discord told me I couldn't use normal looping for vectors. And when I tested it, it returned an error. I didn't bother reading the error because I just assumed he was correct. I tested it just now and it worked fine. https://code.sololearn.com/cnh2U1XQ2TIk/?ref=app That brings up a new question. Can these iterators be used for other containers like arrays? Because I assumed they were strictly for vectors.
8th Feb 2019, 4:11 PM
Daniel Cooper
Daniel Cooper - avatar
+ 1
code learner Feel free to answer this second question. Thanks for your answer btw.
8th Feb 2019, 4:12 PM
Daniel Cooper
Daniel Cooper - avatar
+ 1
KrOW This is exactly what I tried to find, but for some reason it wouldn't show up for me xD. Thank you.
8th Feb 2019, 4:49 PM
Daniel Cooper
Daniel Cooper - avatar