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



描述

C++ 函式std::algorithm::copy_if() 在謂詞對值返回 true 時,將元素範圍複製到新位置。

宣告

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

C++11

template <class InputIterator, class OutputIterator, class UnaryPredicate>
OutputIterator copy_if(InputIterator first,InputIterator last,
   OutputIterator result,UnaryPredicate pred);

引數

  • first - 搜尋序列初始位置的輸入迭代器。

  • last - 搜尋序列最終位置的輸入迭代器。

  • result - 新序列中初始位置的輸出迭代器。

  • pred - 一元謂詞,它接受一個引數並返回一個布林值。

返回值

返回一個指向寫入結果序列的最後一個元素之後的元素的迭代器。

異常

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

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

時間複雜度

在之間的距離上線性firstlast.

示例

以下示例演示了 std::algorithm::copy_if() 函式的使用。

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

using namespace std;

bool predicate(int n) {
   return (n %2 != 0);
}

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

   copy_if(v1.begin(), v1.end(), v2.begin(), predicate);

   cout << "Following are the Odd numbers from vector" << endl;

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

   return 0;
}

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

Following are the Odd numbers from vector
1
3
5
algorithm.htm
廣告