现在接着上篇的,写一来标识vector 的元素的对象迭代器iterator:
还是通过具体代码举例:
下面我讲了一个我暑期团队的故事哦~~:
#include<iostream> #include<vector> using namespace std; int main() { vector<string> myteam; myteam.push_back("Kai She"); myteam.push_back("Cai Baobao"); myteam.push_back("This is me"); vector<string>::iterator myIte; //迭代器iterator的引用方法 vector<string>::const_iterator ite; // 常量迭代器,不能引用它来更改它所引用的元素,但是它本身可以更改 cout <<" Your teams are:\n"; for (ite = myteam.begin(); ite != myteam.end(); ++ite)//遍历容器 cout << "\t " << *ite << endl; cout <<" Because Kai She goes to work, Chen Baobao student comes:\n"; myIte = myteam.begin();//更改元素的值,,,此处表示更改第一个元素的值 *myIte = "Chen Baobao";//队长走了,换成了另一个队友~~ cout << "\n Now ,your teams are:\n"; for ( ite = myteam.begin(); ite != myteam.end(); ++ite) cout << *ite << endl; cout <<"\n The teams name ' " << *myIte << " ' has " <<(*myIte).size() << " letters in it.\n";//这个方法不大好 cout << "\n The teams name ' " << *myIte << " ' has " << myIte->size() << " letters in it\n";//第二种方法 cout << "You find a member join in your team\n" ; myteam.insert(myteam.begin(), " Xing Baobao");//添加新的成员,直接加入了一个新成员 cout << " Because you are not excellent enough , you were pop" << endl; myteam.erase(myteam.begin() + 2);//我被我的团队踢出去了~~~哈哈 cout <<"\n Your teams :\n"; for (ite = myteam.begin(); ite != myteam.end(); ++ite) cout << *ite << endl; }
可以顺便看一下运行结果就可以很清楚的理解iterator的用法了~~
具体例子我写的是自己的队员,通过string对象的myIte 的迭代器:用来标识vector中的一个特定元素的值它是vector中引用一种元素的方法;
在遍历容器时:end()成员函数返回容器中最后一个元素之后的迭代器(不是最后一个元素),所以,不能从end()返回的迭代器中获取值。
在删除一个一个元素时用erase,如果要从在内删除的话,可以在begin()后面直接加数字就行:例如要删除第3个元素:
myteam.erase(myteam.begin() + 2);
所以vector以及iterator的基本用法先写这么点了~~~