主程序如下,当从cin中读入任何数据都没有问题
int main()
{
StrVec sv{ "i","dont","understand" };
for (auto p = sv.begin(); p != sv.end(); p++)
cout << p << " ";
cout << endl;
cout << sv.size() << " " << sv.capacity() << endl;
string s;
while (getline(cin, s)) {
sv.push_back(s);
for (auto p = sv.begin(); p != sv.end(); p++)
cout << *p << " ";
cout << endl;
cout << sv.size() << " " << sv.capacity() << endl;
}
这是试运行效果。
但是读取文件中的内容时就出问题:
int main()
{
/*StrVec sv{ "i","dont","understand" };
for (auto p = sv.begin(); p != sv.end(); p++)
cout << *p << " ";
cout << endl;
cout << sv.size() << " " << sv.capacity() << endl;
string s;
while (getline(cin, s)) {
sv.push_back(s);
for (auto p = sv.begin(); p != sv.end(); p++)
cout << *p << " ";
cout << endl;
cout << sv.size() << " " << sv.capacity() << endl;
}/
ifstream in("test.txt");
if (!in) {
cout << "无法打开输入文件" << endl;
EXIT_FAILURE;
}
runQueries(in);
system("pause");
return 0;
}
查看调用堆栈,感觉问题应该是在这里
TextQuery::TextQuery(ifstream &in):vs()
{
string line, word;
while (getline(in, line))
vs.push_back(line);****查看堆栈返回到这里***
for (size_t i = 0; i != vs.size(); i++) {
stringstream sm(*(vs.begin()+i));
while (sm >> word)
m[word].push_back(i + 1);//绑定每个单词和它出现的行号。
}
}
这个问题是C++Primer 5th里第十三章的13.42里的题。
(在你的TextQuery和QueryResult类中用StrvVec类代替vector)
经过反复的测验,我认为可以确定StrVec类是没有问题,但是不明白我定义的push_back读取cin时没有问题,读取文件时就出现问题。