无法将vector <string>输出到文件</string>

时间:2013-01-27 23:05:19

标签: c++ vector cout

我是C ++的新手。我无法将数据输出到文件。我正在使用迭代器打印出地图。 print方法将i作为键值,并打印出相应的向量。现在,当我使用cout&lt;&lt;正常输出时,这完全正常。但是当我尝试将相同的输出放入文件时,我的程序崩溃了。我知道它是outfile中的*它&lt;&lt;崩溃它的行,因为如果我用一些随机字符串替换它,它会将它输出到文件中。另外,我知道print方法中的参数没有引起任何问题,因为我可以将该方法直接传递给程序的main函数并获得相同的错误。任何帮助将非常感谢如何解决这个问题,谢谢! 这是我发生错误的打印方法:

    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
}

2 个答案:

答案 0 :(得分:2)

您是否同时使用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()是元素刚刚过去向量的结尾。然后,您尝试访问该位置不存在(并且无效)的元素,因此失败。相反,你需要在循环中移动它,这应该是

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
}

答案 1 :(得分:2)

@slugonamission已经给你正确的答案,所以我只是要指出你的功能实际上可以简化并且不易出错。我写这个作为答案只是因为需要代码格式化,否则我会将其发布在评论中:

void print(int i, vector<string> v, ostream& o)
{
    sort(begin(v), end(v));
    v.erase(unique(begin(v), end(v))); // Do this in one step, no iterator mess
    for (auto const& s : v) // Avoid manual iteration cycles if you can
    {
        o << i << ":" << s << endl;
        ...
    }
}

修改

正如@juanchopanza正确指出的那样,实现同样目标的更快捷的方法是将矢量的内容传输到关联容器中以确保唯一性。这将允许您通过const &传递向量:

void print(int i, vector<string> const& v, ostream& o)
{
    unordered_set<string> c(begin(v), end(v));
    for (auto const& s : c)
    {
        o << i << ":" << s << endl;
    }
}