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 和返回的迭代器之间的范围内的对象。
异常
如果任何元素比较、元素赋值或迭代器操作抛出异常,则抛出异常。
请注意,无效参数会导致未定义行为。