我正在尝试使用remove_copy_if将iterable
直接复制到stdout
ostream_iterator。remove_copy_if
保证return value
是输出范围末端的iterator
。此返回值可用于通过找出输出迭代器的开始和返回迭代器之间的距离来确定复制到目标的元素的数量。这在使用容器时是有意义的,但是如果它是ostream_iterator
,如何使用相同的功能来确定复制到目标的元素的数量。
以下示例应该对我可能想要实现的目标更有意义
#include<vector>
#include<iterator>
#include<algorithm>
#include<functional>
#include<iostream>
#include <time.h>
using namespace std;
int main() {
int rawdata[] = {1,2,3,4,5,6,7,8,9,10,11};
vector<int> data(20);
vector<int>::iterator curr = remove_copy_if(rawdata,rawdata + sizeof(rawdata)/sizeof(rawdata[0]),data.begin(),bind2nd(greater<int>(),10));
wcout<<L"No of data copied = "<<curr - data.begin()<<endl;
for(int i=0;i<10;i++) {
int some_value = rand()%20 + 1;
ostream_iterator<int> curr = remove_copy_if(data.begin(),data.end(),ostream_iterator<int>(cout),bind2nd(less<int>(),some_value));
//if (curr - what???? > 0)
cout<<endl;
}
return 0;
}
我遇到了以下非线程安全,不是那么优雅的解决方案来完成这项工作。
#include<vector>
#include<iterator>
#include<algorithm>
#include<functional>
#include<iostream>
#include <time.h>
#include <algorithm>
using namespace std;
template<class _Fn1>
class counter
: public std::unary_function<typename _Fn1::argument_type, bool>
{
public:
explicit counter(const _Fn1& _Func)
: _Functor(_Func) {
count = countTrue = countFalse = 0;
}
bool operator()(const typename _Fn1::argument_type& _Left) const
{
count++;
if (_Functor(_Left)) {
countTrue++;
return true;
} else {
countFalse++;
return false;
}
}
static int count, countTrue,countFalse;
protected:
_Fn1 _Functor; // the functor to apply
};
template<class _Fn1>
int counter<_Fn1>::count=0,counter<_Fn1>::countTrue=0,counter<_Fn1>::countFalse=0;
int main() {
int rawdata[] = {1,2,3,4,5,6,7,8,9,10,11};
vector<int> data(20);
vector<int>::iterator curr = remove_copy_if(rawdata,rawdata + sizeof(rawdata)/sizeof(rawdata[0]),data.begin(),bind2nd(greater<int>(),10));
wcout<<L"No of data copied = "<<curr - data.begin()<<endl;
for(int i=0;i<10;i++) {
int some_value = rand()%20 + 1;
ostream_iterator<int> curr = remove_copy_if(data.begin(),data.end(),ostream_iterator<int>(cout),counter<binder2nd<less<int>>>(bind2nd(less<int>(),some_value)));
if (counter<binder2nd<less<int>>>::countFalse) {
cout<<endl<<"No of data printed = "<<counter<binder2nd<less<int>>>::countFalse<<endl;
}
}
return 0;
}