在大量使用 Haskell 和一般的函数式语言之后,我正在学习 C++,我发现我一直在尝试解决同样的问题:
- 从输入流中读取一些数据
- 根据特定算法对它们进行标记
- 处理 token
如果这是 Haskell,我可以简单地利用一切都是惰性的这一事实,并根据我的想法编写我的转换,然后它会在下游被消耗时得到应用。甚至还有库执行这种精确模式(conduit 和 pipes)。
假设我想获取序列 1 2 3 4 5 6 ...
并输出 12 34 56 ...
。我可以看到如何编写对流进行操作并就地处理数据的临时代码。但是我想知道是否有一种抽象机制允许我通过(以任何可以想到的方式)从另一个流转换数据来构建新流。这种抽象应该允许我缓冲数据在我处理它时,不仅仅是单个元素到新值的简单映射。
以下是限制:
- 除了 stdlib,我无法使用任何其他库。
- 它必须在 C++03 上工作(意味着没有 C++11 功能。)
如果您在想,这是作业吗? 好吧,我收到了很多类作业,这些作业要求我处理数据流(这就是没有库和 C++03 限制)。并不是我不知道如何使用 while
循环来做到这一点,而是我想知道 STL 中是否存在现有的流抽象,只是等待被发现和使用。
但如果唯一的方法是使用 C++11,那么我想知道。
最佳答案
概念代码,未经测试。 成像有很多错误检查和正确的语法。
struct add : public std::binary_function<int,int,int> {
int operator() (int a, int b) {return (a + b);}
};
template<typename inType, typename dType, typename outType, class binFunc>
outType Transformer(inType& inStream, outType& outStream, binFunc func) {
dType a, b;
// Read some data from an input stream
// Tokenize them based on a specific algorithm
inStream>> a >> b;
//outStream << func(a, b);
return func(a,b); // Process the tokens
}
int main() {
std::ifstream in("input.dat", std::ifstream::in); // , std::ios::binary
std::ofstream out("output.dat");
struct add adder; // to Process the tokens
out << Transformer(in, out, adder);
return exit_success;
}
关于c++ - 如何用 C++ 编写自定义流转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26313485/