参考这种用法:
int a[3]={1,2,3};
copy(a,a+3,ostream_iterator<int>(cout," "));
以及
ostream_iterator 类 | Microsoft Learn 中的函数签名,可以编写出 StdioIterator,同样支持 copy 函数的调用。
#include <stdio.h>
#include <algorithm>
using namespace std;template <typename T>
class StdioIterator {
public:StdioIterator(FILE* fp,const char* delim="") :fp(fp),DELIM(delim) {}StdioIterator operator++(void) { return *this; }StdioIterator& operator++(int) { return *this; }StdioIterator& operator*(void) { return *this; }StdioIterator& operator=(const T& val);private:FILE* fp;const char* DELIM;
};template <>
StdioIterator<int>& StdioIterator<int>::operator=(const int& val) {fprintf(fp,"%d%s",val,DELIM);return *this;
}template <>
StdioIterator<double>& StdioIterator<double>::operator=(const double& val) {fprintf(fp,"%g%s",val,DELIM);return *this;
}int main(void) {int a[3]={5,2,0};copy(a,a+3,StdioIterator<int>(stdout,"+"));putchar('\n');double b[2]={1.3,1.4};copy(b,b+2,StdioIterator<double>(stdout," "));return 0;
}