STL 之swap, iter_swap, swap_ranges

来源:互联网 发布:淘宝水果模特 编辑:程序博客网 时间:2024/05/15 14:41

作用:交换元素

声明:

  1. #include <algorithm>  
  2. template<class Type>  
  3. void swap(Type& objcet1, Type& objec2);  
  4.   
  5. template<class forwardItr1,class forwardItr2>  
  6. void iter_swap(forwardItr1 first,forwardItr2 scecod);  
  7.   
  8. template<class forwardItr1, class forwardItr2>  
  9. forwardItr2 swap_ranges(forwardItr1 first,forwardItr1 last, forwardItr2 first2);  

示例代码:

  1. #include <iostream>  
  2. #include <list>  
  3.   
  4. #include <string>  
  5. #include <numeric>  
  6. #include <iterator>  
  7. #include <vector>  
  8. #include <functional>  
  9.   
  10. #include <algorithm>  
  11.   
  12. using namespace std;  
  13.   
  14. int main() {  
  15.     char cList[10] = {'A','B','C','D','F','G','H','I','J','K'};  
  16.     vector<char> charList(cList,cList+10);  
  17.   
  18.     vector<char>::iterator charItr;  
  19.     ostream_iterator<char> screen(cout," ");  
  20.     cout << "charList:" << endl;  
  21.     copy(charList.begin(),charList.end(),screen);  
  22.     cout << endl;  
  23.   
  24.     // 容器内部元素交互  
  25.     swap(charList[0],charList[1]);  
  26.     cout << "charList.swap" << endl;  
  27.     copy(charList.begin(),charList.end(),screen);  
  28.     cout << endl;  
  29.   
  30.     // 用迭代器进行交互  
  31.     iter_swap(charList.begin() + 2,charList.begin() + 3);  
  32.     cout << "charList.iter_swap" << endl;  
  33.     copy(charList.begin(),charList.end(),screen);  
  34.     cout << endl;  
  35.   
  36.     charItr = charList.begin() + 4;  
  37.     iter_swap(charItr,charItr + 1);  
  38.     cout << "charList.iter_swap" << endl;  
  39.     copy(charList.begin(),charList.end(),screen);  
  40.     cout << endl;  
  41.   
  42.     int list[10] = {1,2,3,4,5,6,7,8,9,10};  
  43.     vector<int> intList(list,list + 10);  
  44.     ostream_iterator<int> screenInt(cout, " ");  
  45.     cout << "intList:" << endl;  
  46.     copy(intList.begin(),intList.end(),screenInt);  
  47.     cout << endl;  
  48.   
  49.     swap_ranges(intList.begin(),intList.begin()+4,intList.begin()+5);  
  50.     cout << "intList.swap_ranges:" << endl;  
  51.     copy(intList.begin(),intList.end(),screenInt);  
  52.     cout << endl;  
  53.   
  54.     // 不同容器之间元素交互  
  55.     swap_ranges(list,list+10,intList.begin());  
  56.     cout << "list:" << endl;  
  57.     copy(list,list+10,screenInt);  
  58.     cout << endl;   
  59.     cout << "intList: " << endl;  
  60.     copy(intList.begin(),intList.end(),screenInt);  
  61.     cout << endl;  
  62.   
  63.     return 0;  
  64. }  

运行结果:

charList:
A B C D F G H I J K
charList.swap
B A C D F G H I J K
charList.iter_swap
B A D C F G H I J K
charList.iter_swap
B A D C G F H I J K
intList:
1 2 3 4 5 6 7 8 9 10
intList.swap_ranges:
6 7 8 9 5 1 2 3 4 10
list:
6 7 8 9 5 1 2 3 4 10
intList:
1 2 3 4 5 6 7 8 9 10

0 0
原创粉丝点击