Now, in the previous article, write an object iterator iterator that identifies the elements of the vector:
or through specific code examples:
Below I tell a story of my summer team:
1#include <iostream>2#include <vector>3 using namespacestd;4 intMain ()5 {6vector<string>MyTeam;7Myteam.push_back ("Kai She");8Myteam.push_back ("Cai Baobao");9Myteam.push_back ("This is me");Ten Onevector<string>:: Iterator myite; Reference method for iterator iterator Avector<string>:: const_iterator ite;//const iterator, cannot reference it to change the element it refers to, but it can change itself - -cout <<"Your Teams are:\n"; the for(ite = Myteam.begin (); ITE! = Myteam.end (); + +ite)//Traversal container -cout <<"\ t"<< *ite <<Endl; - -cout <<"Because Kai She goes to work, Chen Baobao student comes:\n"; +Myite =Myteam.begin ();//Change the value of an element, where the value of the first element is changed -*myite ="Chen Baobao";//The captain has gone, replaced by another teammate ~ ~ +cout <<"\ n Now, your teams are:\n"; A for(ite = Myteam.begin (); ITE! = Myteam.end (); + +ite) atcout << *ite <<Endl; - -cout <<"\ n The teams name '"<< *myite <<"' has" -<< (*myite). Size () <<"Letters in it.\n";//This method is not good -cout <<"\ n The teams name '"<< *myite <<"' has" -<< myite->size () <<"Letters in it\n";//The second method in -cout <<"You find a member joins in your team\n" ; toMyteam.insert (Myteam.begin (),"Xing Baobao")///Add a new member and join a new member directly + -cout <<"Because you aren't excellent enough, you were pop"<<Endl; the myteam.erase (Myteam.begin () + 2);//I was kicked out by my team ~ ~ ~ Haha * $cout <<"\ Your teams: \ n";Panax Notoginseng for(ite = Myteam.begin (); ITE! = Myteam.end (); + +ite) -cout << *ite <<Endl; the + A the}
Can be seen by the way the results of the operation can be very clear understanding of the use of iterator ~ ~
For example, I'm writing my own team. An iterator to the myite of a string object: A value used to identify a particular element in a vector it is a method of referencing an element in a vector;
When traversing a container: the end () member function returns an iterator (not the last element) after the last element in the container, so the value cannot be obtained from the iterator returned by end ().
When deleting an element with erase, if you want to delete it, you can add a number directly after the Begin (): For example, to delete the 3rd element:
Myteam.erase (Myteam.begin () + 2);
So the basic usage of vector and iterator is to write this point first.
Blacjack knowledge points to be added in the Game 2