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



描述

C++ 函式std::algorithm::copy_backward() 以反向順序將元素範圍複製到新位置。

宣告

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

C++98

template <class BidirectionalIterator1, class BidirectionalIterator2>
BidirectionalIterator2 copy_backward(BidirectionalIterator1 first,
   BidirectionalIterator1 last, BidirectionalIterator2 result);

引數

  • first - 雙向迭代器,指向序列中的初始位置。

  • last - 雙向迭代器,指向序列中的最終位置。

  • result - 雙向迭代器,指向目標序列中末尾之後的那個位置。

返回值

返回一個迭代器,指向目標序列中已複製元素的第一個元素。

異常

如果元素賦值或迭代器上的操作引發異常,則丟擲異常。

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

時間複雜度

線性於firstlast.

之間的距離

示例

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

using namespace std;

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

   copy_backward(v1.begin(), v1.end(), v2.end());

   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
2
3
4
5
algorithm.htm
廣告