C++11标准模板(STL)- 算法(std::iter_swap)

定义于头文件 <algorithm>

算法库提供大量用途的函数(例如查找、排序、计数、操作),它们在元素范围上操作。注意范围定义为 [first, last) ,其中 last 指代要查询或修改的最后元素的后一个元素。

交换两个迭代器所指向的元素

std::iter_swap

template< class ForwardIt1, class ForwardIt2 >
void iter_swap( ForwardIt1 a, ForwardIt2 b );

(C++20 前)

template< class ForwardIt1, class ForwardIt2 >
constexpr void iter_swap( ForwardIt1 a, ForwardIt2 b );

(C++20 起)

交换给定的迭代器所指向的元素的值。

参数

a, b-指向要交换的元素的迭代器
类型要求
- ForwardIt1, ForwardIt2 必须满足遗留向前迭代器 (LegacyForwardIterator) 的要求。
- *a, *b 必须满足可交换 (Swappable) 的要求。

返回值

(无)

复杂度

常数

 可能的实现

template<class ForwardIt1, class ForwardIt2>
constexpr void iter_swap(ForwardIt1 a, ForwardIt2 b) // C++20 起为 constexpr
{
   using std::swap;
   swap(*a, *b);
}

调用示例

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

struct Cell
{
    int x;
    int y;
    Cell &operator+=(Cell &cell)
    {
        x += cell.x;
        y += cell.y;
        return *this;
    }
};

std::ostream &operator<<(std::ostream &os, const Cell &cell)
{
    os << "{" << cell.x << "," << cell.y << "}";
    return os;
}

int main()
{
    auto func1 = []()
    {
        static Cell cell = {99, 100};
        cell.x += 2;
        cell.y += 2;
        return cell;
    };

    std::vector<Cell> cells_1(6);
    std::generate_n(cells_1.begin(), cells_1.size(), func1);
    std::list<Cell> cells_2(8);
    std::generate_n(cells_2.begin(), cells_2.size(), func1);

    std::cout << "original : " << std::endl;
    std::cout << "cells_1 : ";
    std::copy(cells_1.begin(), cells_1.end(), std::ostream_iterator<Cell>(std::cout, " "));
    std::cout << std::endl;
    std::cout << "cells_2 : ";
    std::copy(cells_2.begin(), cells_2.end(), std::ostream_iterator<Cell>(std::cout, " "));
    std::cout << std::endl << std::endl;

    auto it1 = cells_1.begin();
    auto it2 = cells_2.begin();
    for (; it1 != cells_1.end(); it1++, it2++)
    {
        std::iter_swap(it1, it2);
    }

    std::cout << "new : " << std::endl;
    std::cout << "cells_1 : ";
    std::copy(cells_1.begin(), cells_1.end(), std::ostream_iterator<Cell>(std::cout, " "));
    std::cout << std::endl;
    std::cout << "cells_2 : ";
    std::copy(cells_2.begin(), cells_2.end(), std::ostream_iterator<Cell>(std::cout, " "));
    std::cout << std::endl << std::endl;
}

输出

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值