描述
C++ 函數std::algorithm::copy_if()如果謂詞對值返回 true,則將一係列元素複製到新位置。
聲明
以下是 std::algorithm::copy_if() 函數形式 std::algorithm 頭文件的聲明。
C++11
template <class InputIterator, class OutputIterator, class UnaryPredicate>
OutputIterator copy_if(InputIterator first,InputIterator last,
OutputIterator result,UnaryPredicate pred);
參數
first− 將迭代器輸入到搜索序列的初始位置。
last− 將迭代器輸入到搜索序列的最終位置。
result− 將迭代器輸出到新序列中的初始位置。
pred- 一元謂詞接受一個參數並返回一個布爾值。
返回值
返回指向結果序列中寫入的最後一個元素之後的元素的迭代器。
異常
如果元素賦值或迭代器上的操作拋出異常,則拋出異常。
請注意無效的參數會導致未定義的行為。
時間複雜度
之間的距離呈線性第一的至最後的。
示例
下麵的例子展示了 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
相關用法
- C++ Algorithm copy_backward()用法及代碼示例
- C++ Algorithm copy_n()用法及代碼示例
- C++ Algorithm copy()用法及代碼示例
- C++ Algorithm count_if()用法及代碼示例
- C++ Algorithm count()用法及代碼示例
- C++ Algorithm remove_if()用法及代碼示例
- C++ Algorithm remove()用法及代碼示例
- C++ Algorithm max_element()用法及代碼示例
- C++ Algorithm equal()用法及代碼示例
- C++ Algorithm set_union()用法及代碼示例
- C++ Algorithm next_permutation()用法及代碼示例
- C++ Algorithm upper_bound()用法及代碼示例
- C++ Algorithm minmax()用法及代碼示例
- C++ Algorithm remove_copy_if()用法及代碼示例
- C++ Algorithm find_if_not()用法及代碼示例
- C++ Algorithm for_each()用法及代碼示例
- C++ Algorithm pop_heap()用法及代碼示例
- C++ Algorithm adjacent_find()用法及代碼示例
- C++ Algorithm replace_if()用法及代碼示例
- C++ Algorithm replace()用法及代碼示例
注:本文由純淨天空篩選整理自 C++ Algorithm Library - copy_if() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。