C++ 演算法庫 - iter_swap() 函式



描述

C++ 函式std::algorithm::iter_swap()交換兩個迭代器指向的物件的值。它使用函式swap(未限定)來交換元素。

宣告

以下是來自 std::algorithm 標頭檔案的 std::algorithm::iter_swap() 函式的宣告。

C++98

template <class ForwardIterator1, class ForwardIterator2>
void iter_swap (ForwardIterator1 a, ForwardIterator2 b);

引數

  • a - 第一個前向迭代器物件。

  • b - 第二個前向迭代器物件。

返回值

異常

如果丟擲異常,則丟擲異常swap函式。

請注意,無效引數會導致未定義的行為。

時間複雜度

常數。

示例

以下示例顯示了 std::algorithm::iter_swap() 函式的使用方法。

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main(void) {
   vector<int> v1 = {1, 2, 3, 4, 5};
   vector<int> v2 = {10, 20, 30, 40, 50};

   iter_swap(v1.begin(), v2.begin());
   iter_swap(v1.begin() + 1, v2.begin() + 2);

   cout << "Vector v2 contains following elements" << endl;

   for (auto it = v2.begin(); it != v2.end(); ++it)
      cout << *it << endl;

   return 0;
}

讓我們編譯並執行上述程式,這將產生以下結果:

Vector v2 contains following elements
1
20
2
40
50
algorithm.htm
廣告