function template
<algorithm>
std::remove_copy
template <class InputIterator, class OutputIterator, class T> OutputIterator remove_copy (InputIterator first, InputIterator last, OutputIterator result, const T& val);
Copy range removing value
Copies the elements in the range [first,last)
to the range beginning at result, except those elements that compare equal to val.
The resulting range is shorter than [first,last)
by as many elements as matches in the sequence, which are "removed".
該函式使用 operator==
將單個元素與 val 進行比較。
此函式模板的行為等同於
1 2 3 4 5 6 7 8 9 10 11 12 13
|
template <class InputIterator, class OutputIterator, class T>
OutputIterator remove_copy (InputIterator first, InputIterator last,
OutputIterator result, const T& val)
{
while (first!=last) {
if (!(*first == val)) {
*result = *first;
++result;
}
++first;
}
return result;
}
|
引數
- first, last
- Forward iterators to the initial and final positions in a sequence of elements supporting being compared to a value of type T. The range used is
[first,last)
, which contains all the elements between first and last, including the element pointed by first but not the element pointed by last.
- result
- 輸出迭代器,指向儲存結果序列的範圍的起始位置。
The pointed type shall support being assigned the value of an element in the range [first,last)
.
- val
- Value to be removed.
這些範圍不應重疊。
返回值
An iterator pointing to the end of the copied range, which includes all the elements in [first,last)
except those that compare equal to val.
示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
// remove_copy example
#include <iostream> // std::cout
#include <algorithm> // std::remove_copy
#include <vector> // std::vector
int main () {
int myints[] = {10,20,30,30,20,10,10,20}; // 10 20 30 30 20 10 10 20
std::vector<int> myvector (8);
std::remove_copy (myints,myints+8,myvector.begin(),20); // 10 30 30 10 10 0 0 0
std::cout << "myvector contains:";
for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
return 0;
}
|
輸出
myvector contains: 10 30 30 10 10 0 0 0
|
複雜度
Linear in the distance between first and last: Compares each element, and performs an assignment operation for those not removed.
資料競爭
訪問範圍 [first,last)
中的物件。
修改 result 和返回的迭代器之間的範圍內的物件。
異常
如果任何元素比較、元素賦值或迭代器操作丟擲異常,則丟擲異常。
請注意,無效引數會導致未定義行為。