C++标准库---advance()&distance()&iter_swap()

advance:

void advance(pos,n);

1.使名为pos的input迭代器步进(或步退)n个元素;

2.对Bidirectional迭代器和Random Access迭代器而言,n可为负值,表示向后退;

3.advance()并不检查迭代器是否超过序列的end()(因为迭代器通常不知道其所操作的容器,因此无从检查)。所以,调用advance()有可能导致未定义行为----因为对“序列尾端调用operator++”是一种未定义的操作行为;

4.此函数总能根据迭代器类型采用最佳方案,这归功于迭代器特征的运用。面对Random Access迭代器,此函数只是简单的调用pos+=n,因此,具有常量复杂度;对于其他任何类型的迭代器则调用++pos(或--pos,如果n为负)n次,因此对于其他任何类型迭代器,本函数具有线性复杂度。

5.如果需要更换容器或迭代器种类,应该使用advance()而不是operator+=。但是存在“在不提供Random Access迭代器”的容器中,性能变差;

6.advance()没有返回值;

 示例代码:

#include<iostream>
#include<list>
#include<algorithm>

using namespace std;

int main()
{
	list<int> coll;

	for(int i=1;i<=9;i++)
	{
		coll.push_back(i);
	}

	list<int>::iterator pos=coll.begin();

	cout<<*pos<<endl;

	advance(pos,3);

	cout<<*pos<<endl;

	advance(pos,-1);

	cout<<*pos<<endl;

	system("pause");
	return 0;
}

运行结果:

1

4

3

distance()

函数distance()用来处理两个迭代器之间的距离
Dist distance(pos1,pos2);

1.传回两个input迭代器pos1和pos2之间的距离;
2.两个迭代器都必须指向同一个容器;

3.对于random access迭代器,此函数仅仅只是传回pos2-pos1,因此具备常数复杂度;

4.对于其他迭代器类型,distance()会不断递增pos1,直到抵达pos2为止,然后传回递增次数,也就是说其他类型的迭代器,distance()具备线性复杂度,所以对于non-random access迭代器,尽力避免使用此函数;

5.如果需要更换容器型别和迭代器的型别,就应该使用distance()而不是operator-,但是存在对“non-random access迭代器”性能变差的问题,并且第一个迭代器绝对不能位于第二个迭代器之后,否则未定义行为;


代码示例:

//distance()
#include<iostream>
#include<vector>
#include<algorithm>
#include<iterator>


using namespace std;

int main()
{
	vector<int> coll; 

	for(int i=-3;i<=9;i++)
	{
		coll.push_back(i);
	}

	vector<int>::iterator pos;

	pos=find(coll.begin(),coll.end(),5);

	if(pos!=coll.end())
	{
		cout<<"distance between begining and 5:"<<distance(coll.begin(),pos)<<endl;
	}
	else
	{
		cout<<"5 not found"<<endl;
	}

	system("pause");
	return 0;
}

运行结果:distance between begining and 5:8


iter_swap

void iter_swap(pos1,pos2);

1.交换迭代器pos1和迭代器pos2所指的值

2.迭代器的型别不必相同,但其所指的两个值必须可以相互赋值

代码示例:

#include<iostream>
#include<list>
#include<iterator>
#include<algorithm>

using namespace std;

int main()
{
	list<int> coll;

	for(int i=1;i<=9;i++)
	{
		coll.push_back(i);
	}

	copy(coll.begin(),coll.end(),ostream_iterator<int>(cout," "));
	cout<<endl;

	iter_swap(coll.begin(),++coll.begin());//交换迭代器所指元素的内容

	copy(coll.begin(),coll.end(),ostream_iterator<int>(cout," "));
	cout<<endl;

	iter_swap(coll.begin(),--coll.end());

	copy(coll.begin(),coll.end(),ostream_iterator<int>(cout," "));
	cout<<endl;

	system("pause");
	return 0;
}

运行结果:

1 2 3 4 5 6 7 8 9

2 1 3 4 5 6 7 8 9

9 1 3 4 5 6 7 8 2

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值