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

相关文章:

  • 2022-02-08
  • 2022-12-23
  • 2022-12-23
  • 2022-01-18
  • 2022-01-07
  • 2021-08-02
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-01-19
  • 2022-12-23
  • 2021-08-20
  • 2022-12-23
相关资源
相似解决方案