STL 之swap, iter_swap, swap_ranges

38 篇文章 0 订阅

返回


作用:交换元素

声明:

#include <algorithm>
template<class Type>
void swap(Type& objcet1, Type& objec2);

template<class forwardItr1,class forwardItr2>
void iter_swap(forwardItr1 first,forwardItr2 scecod);

template<class forwardItr1, class forwardItr2>
forwardItr2 swap_ranges(forwardItr1 first,forwardItr1 last, forwardItr2 first2);

示例代码:

#include <iostream>
#include <list>

#include <string>
#include <numeric>
#include <iterator>
#include <vector>
#include <functional>

#include <algorithm>

using namespace std;

int main() {
	char cList[10] = {'A','B','C','D','F','G','H','I','J','K'};
	vector<char> charList(cList,cList+10);

	vector<char>::iterator charItr;
	ostream_iterator<char> screen(cout," ");
	cout << "charList:" << endl;
	copy(charList.begin(),charList.end(),screen);
	cout << endl;

	// 容器内部元素交互
	swap(charList[0],charList[1]);
	cout << "charList.swap" << endl;
	copy(charList.begin(),charList.end(),screen);
	cout << endl;

	// 用迭代器进行交互
	iter_swap(charList.begin() + 2,charList.begin() + 3);
	cout << "charList.iter_swap" << endl;
	copy(charList.begin(),charList.end(),screen);
	cout << endl;

	charItr = charList.begin() + 4;
	iter_swap(charItr,charItr + 1);
	cout << "charList.iter_swap" << endl;
	copy(charList.begin(),charList.end(),screen);
	cout << endl;

	int list[10] = {1,2,3,4,5,6,7,8,9,10};
	vector<int> intList(list,list + 10);
	ostream_iterator<int> screenInt(cout, " ");
	cout << "intList:" << endl;
	copy(intList.begin(),intList.end(),screenInt);
	cout << endl;

	swap_ranges(intList.begin(),intList.begin()+4,intList.begin()+5);
	cout << "intList.swap_ranges:" << endl;
	copy(intList.begin(),intList.end(),screenInt);
	cout << endl;

	// 不同容器之间元素交互
	swap_ranges(list,list+10,intList.begin());
	cout << "list:" << endl;
	copy(list,list+10,screenInt);
	cout << endl; 
	cout << "intList: " << endl;
	copy(intList.begin(),intList.end(),screenInt);
	cout << endl;

	return 0;
}

运行结果:

charList:
A B C D F G H I J K
charList.swap
B A C D F G H I J K
charList.iter_swap
B A D C F G H I J K
charList.iter_swap
B A D C G F H I J K
intList:
1 2 3 4 5 6 7 8 9 10
intList.swap_ranges:
6 7 8 9 5 1 2 3 4 10
list:
6 7 8 9 5 1 2 3 4 10
intList:
1 2 3 4 5 6 7 8 9 10


  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Yours风之恋

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值