首页 > 编程语言 > 详细

C++ iter_swap()运用实例

时间:2019-12-28 20:58:49      阅读:103      评论:0      收藏:0      [点我收藏+]

iter_swap函数用来交换两个迭代器所指向的元素值,迭代器类型不必相同,但其所指的值必须可以相互赋值(assignable)。

myprint.hpp

#include <iostream>
#include <string>

template <typename T>
inline void PRINT_ELEMENTS(const T& coll, const std::string& optstr = "")
{
    std::cout << optstr;
    for (const auto& elem : coll)
    {
        std::cout << elem << "  ";
    }
    std::cout << std::endl;
}

 

test.cpp

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

#include "myprint.hpp"
using namespace std;

int main()
{
    list<int> list1;
    for (int k = 1; k <= 9;++k) 
    {
        list1.push_back(k);
    }

    PRINT_ELEMENTS(list1);

    iter_swap(list1.begin(),next(list1.begin()));
    PRINT_ELEMENTS(list1);

    iter_swap(list1.begin(),prev(list1.end()));
    PRINT_ELEMENTS(list1);

    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
请按任意键继续. . .

 

代码参考:C++标准库(第2版)

C++ iter_swap()运用实例

原文:https://www.cnblogs.com/herd/p/12112827.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!