//STL示例 advance及distance
#include <iostream>
#include <list>
#include <algorithm> //find use
#include <iterator>
using namespace std;
int iArray[5] = { 1, 2, 3, 4, 5 };
void Display(list<int>& a, const char* s);
int main ()
{
list<int> iList;
list<int>::iterator p=iList.begin();//定义迭代器并指向容器开始
copy(iArray, iArray + 5, inserter(iList,p));//从开头一个个插入元素
//copy(iArray, iArray + 5, front_inserter(iList));//前端插入
Display(iList,"插入后:");
p =find(iList.begin(), iList.end(), 2);
cout << "before: p == " << *p << endl;
advance(p, 2); //等于p+=2;
cout << "after : p == " << *p << endl;
int k = 0;
k=distance(p,iList.end());//等于iList.end()-p
cout << "k == " << k << endl;
return 0;
}
void Display(list<int>& a, const char* s)
{
cout << s << endl;
copy(a.begin(), a.end(),ostream_iterator<int>(cout, " "));//使用空格分开容器各项
cout << endl;
}
STL示例10(advance及distance使用)
最新推荐文章于 2021-09-04 00:44:39 发布
本文通过一个具体的示例展示了如何在C++标准模板库(STL)中使用advance和distance两个函数。示例中首先创建了一个整数列表,并使用find定位到特定元素,之后使用advance移动迭代器位置,并利用distance计算距离。
2526

被折叠的 条评论
为什么被折叠?



