std::swap_ranges 用法

描述:
       交换两个范围的元素。
       在范围 [first1, last1) 和始于 first2 的另一范围间交换元素。

函数定义:

template< class ForwardIt1, class ForwardIt2 >
ForwardIt2 swap_ranges( ForwardIt1 first1, ForwardIt1 last1,
                        ForwardIt2 first2 );

template< class ForwardIt1, class ForwardIt2 >
constexpr ForwardIt2 swap_ranges( ForwardIt1 first1, ForwardIt1 last1,
                                  ForwardIt2 first2 );

参数:
       first1, last1 - 要交换的第一个元素范围
       first2 - 要交换的第二个元素范围的起始

返回值:
       返回始于 first2 的范围中被交换的最末元素后一元素的迭代器。

可能的实现:

template<class ForwardIt1, class ForwardIt2>
ForwardIt2 swap_ranges(ForwardIt1 first1, 
                             ForwardIt1 last1, 
                             ForwardIt2 first2)
{
    while (first1 != last1) {
        std::iter_swap(first1++, first2++);
    }
    return first2;
}

示例:

#include <iostream>
#include <vector>
#include <algorithm>

int main(int argc, char **argv)
{
	std::vector<int> vecInt1 = { 1,2,3,4,5 };
	std::vector<int> vecInt2 = { 6,7,8,9,10 };
	std::swap_ranges(vecInt1.begin(), vecInt1.begin() + 3, vecInt2.begin());
	auto print = [](int nA) {std::cout << nA << " "; };

	std::for_each(vecInt1.begin(), vecInt1.end(), print);//6 7 8 4 5
	std::cout << std::endl;
	std::for_each(vecInt2.begin(), vecInt2.end(), print);//1 2 3 9 10

	return 0;   
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值