我是 C++ 新手。我在将数据输出到文件时遇到问题。我正在使用迭代器打印 map 。 print 方法接受一个键值 i,并打印出它对应的 vector 。现在,当我使用 cout<< 正常输出时,效果非常好,但是当我尝试将相同的输出放入文件中时,我的程序崩溃了。我知道是 outfile<< 行中的 *it 导致了它崩溃,因为如果我用一些随机字符串替换它,它就会将其输出到文件中。另外,我知道 print 方法中的参数不会引起任何问题,因为我可以将该方法直接传输到程序的主函数并得到相同的错误。任何有关如何解决此问题的帮助将不胜感激,谢谢! 这是我发生错误的打印方法:
public: void print(int i, vector<string> in, ostream& outfile) // print method for printing a vector and it's key
{
sort(in.begin(), in.end()); // sort the vector alphabetically first
vector<string>::iterator it;
it= unique(in.begin(), in.end()); // makes sure there are no duplicate strings
in.resize( distance(in.begin(),it) );
for( it = in.begin(); it != in.end(); it++ ) // iterate through it
cout << i << ": "<< *it<<endl; // and print out the key value and each string in the vector
// outfile<< i << ":" << *it<< endl; // prints to file
}
最佳答案
您是否同时使用cout
行?如果是这样,我想我知道它是什么。
不带大括号的 for
循环将执行下一条语句作为其循环体。如果您同时使用 cout
行和 outfile
行,您将打印所有内容,然后在循环之后,it
将位于刚刚过去的位置数组的末尾。然后,您尝试取消引用它并将其写入文件,这当然会失败,因为您取消引用了无效的迭代器。
简短的回答,用大括号将语句括在 for 循环中。
例如,您有以下内容(正确缩进时):
for( it = in.begin(); it != in.end(); it++ ) // iterate through it
cout << i << ": "<< *it<<endl;
outfile<< i << ":" << *it<< endl; // prints to file
最后一行,it = in.end()
,其中 in.end()
是刚刚过去的元素 vector 的末尾。然后,您尝试访问该位置不存在(且无效)的元素,因此失败。相反,您需要将其移至循环内,其应为
for( it = in.begin(); it != in.end(); it++ ) // iterate through it
{
cout << i << ": "<< *it<<endl; // and print out the key value and each string in the vector
outfile<< i << ":" << *it<< endl; // prints to file
}
关于c++ - 无法将 vector <string> 输出到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14553375/