zoukankan      html  css  js  c++  java
  • C++ iter_swap()运用实例

    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版)

  • 相关阅读:
    Leetcode 283. Move Zeroes
    算法总结
    随机森林
    BRICH
    DBSCAN算法
    k-means算法的优缺点以及改进
    soket编程
    手电筒过河
    字符串反转
    URAL 1356. Something Easier(哥德巴赫猜想)
  • 原文地址:https://www.cnblogs.com/herd/p/12112827.html
Copyright © 2011-2022 走看看