【发布时间】:2011-06-16 01:16:39
【问题描述】:
在我最近的question 之后,我正在尝试实现我自己设计的示例。
我有一个基本的结构,但即使在阅读了this,这可能是我见过的最好的教程之后,我仍然很困惑。我想我可能应该将 Chapter._text 转换为流,并为增量运算符做类似的事情
string p = "";
string line;
while ( getline(stream, line) ) {
p += line;
}
return *p;
但我不确定要使用哪个“样板”类型定义以及如何将所有这些东西放在一起。非常感谢您的帮助
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
class Paragraph {
public:
string _text;
Paragraph (string text) {
_text = text;
}
};
class Chapter {
public:
string _text;
/* // I guess here I should do something like:
class Iterator : public iterator<input_iterator_tag, Paragraph> {
}
// OR should I be somehow delegating from istream_iterator ? */
Chapter (string txt_file) {
string line;
ifstream infile(txt_file.c_str());
if (!infile.is_open()) {
cout << "Error opening file " << txt_file << endl;
exit(0);
}
while ( getline(infile, line) ) {
_text += (line + "\n");
}
}
};
int main(int argc, char** argv) {
Chapter c(argv[1]);
// want to do something like:
// for (<Paragraph>::iterator pIt = c.begin(); pIt != c.end(); pIt++) {
// Paragraph p(*pIt);
// // Do something interesting with p
// }
return 0;
}
【问题讨论】:
-
Chapter::Iterator应该如何移动?Chapter类中的唯一数据是成员_text,它存储输入文件 sans 行结尾的 整个 内容。有什么想法? -
谢谢,刚刚更正了行尾。
-
那么...为什么不直接将整个文件读入内存呢?
-
总的想法是能够迭代从Chapter on the fly STL风格中提取的段落,而无需将它们显式存储在容器中。这个例子有点做作,但如果文本文件非常大并且我不想将整个内容再次存储为矢量
,例如 ,它可能会很有用 -
那么……去实现迭代器接口吧!你需要了解什么?我想当你按下“增量”时会发生魔法......你会保留一个指向当前位置的指针吗?