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