首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

std::iter_swap

Defined in header <algorithm>

?

?

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

?

?

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

参数

a, b

-

iterators to the elements to swap

类型要求

-前进1,前进2必须符合先行者的要求。

---%2AA,%2A必须符合可互换的要求。

返回值

%280%29

复杂性

常量。

可能的实施

模板<类ForwardIt 1,类ForwardIt 2>voidITER[医]交换%28ForwardIt1a,ForwardIt2b%29{使用STD::SWAP;交换%28%2AA,%2Ab%29;}

*。

以下是C++中选择排序的实现

二次

代码语言:javascript
复制
#include <random>
#include <vector>
#include <iostream>
#include <algorithm>
#include <functional>
#include <iterator>
 
template<class ForwardIt>
void selection_sort(ForwardIt begin, ForwardIt end)
{
    for (ForwardIt i = begin; i != end; ++i)
        std::iter_swap(i, std::min_element(i, end));
}
 
int main()
{
    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_int_distribution<> dist(-10, 10);
    std::vector<int> v;
    generate_n(back_inserter(v), 20, bind(dist, gen));
 
    std::cout << "Before sort: ";
    copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " "));
 
    selection_sort(v.begin(), v.end());
 
    std::cout << "\nAfter sort: ";
    copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " "));
    std::cout << '\n';
}

二次

产出:

二次

代码语言:javascript
复制
Before sort: -7 6 2 4 -1 6 -9 -1 2 -5 10 -9 -5 -3 -5 -3 6 6 1 8
After sort: -9 -9 -7 -5 -5 -5 -3 -3 -1 -1 1 2 2 4 6 6 6 6 8 10

二次

另见

swap

swaps the values of two objects (function template)

swap_ranges

swaps two ranges of elements (function template)

代码语言:txt
复制
 ? cppreference.com

在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。

扫码关注腾讯云开发者

领取腾讯云代金券

http://www.vxiaotou.com