将向量内容写入文件C++

3

我曾尝试将我的向量内容写入文件中。为此,我编写了以下代码:

int main()
{
    ofstream outputfile("test.txt");
    vector<int>temp;
    temp.push_back(1);
    temp.push_back(2);
    temp.push_back(3);
    for(int i=0;i<temp.size();i++)
        outputfile<<temp[i]<<"\n";
}

当我写下这段代码时,我可以轻松地做到我想要的。文件内容如下:

1 2 3

然而,当我想要将我的向量以相反的顺序写入文件中(如下所示),我什么也得不到。只有空文件。有人能帮忙吗?提前感谢。

for(int i=temp.size()-1;i>=0;i--)
    outputfile<<temp[i]<<"\n";

你要从 vector 的末尾开始计算。 - BoBTFish
@BoBTFish 抱歉,我纠正了这个错误。在我的真实代码中,它是放在正确的位置的。所以,问题不在于此。 - caesar
5
对我来说没问题。如果你的代码实际上在刷新和/或关闭后给出了空文件,那么问题必须存在于你没有展示的某些东西中。 - Angew is no longer proud of SO
到目前为止,你得到的所有答案都没有抓住问题的重点。虽然代码对我也有效,但我会改用reverse_iterator。 - ajcaruana
4个回答

8
您可以使用

标签

std::copy(temp.rbegin(), temp.rend(),
          std::ostream_iterator<int>(outputfile, "\n"));

而这段代码:

for(int i=temp.size()-1;i>=0;i--)
    outputfile<<temp[i]<<"\n";

在我的Windows电脑上,使用VS12运行良好。


人们真的觉得这比一个简单的for循环更易懂吗?无论如何,它并没有真正回答为什么他的for循环不起作用,因为它本应该正常工作。 - Benjamin Lindley
3
一旦你习惯了它,是的(至少我是这样)。因为你不需要查看并确保循环执行它看起来要执行的操作。 - Angew is no longer proud of SO
@BenjaminLindley 是的。在尝试追踪自定义循环中设置条件的奇怪方式(例如从1开始并执行<而不是<=)的错误后,使用算法使代码更易读。 - Zac Howland
@Angew:您仍需要确保参数是正确的。对我来说,这需要的时间和检查这个简单for循环的参数所需的时间相同,但因人而异。 - Benjamin Lindley

5
您可以在一行代码中完成所有操作:
std::copy(temp.rbegin(), temp.rend(), std::ostream_iterator<int>(outputFile, "\n"));

感谢回复。在我的实际问题中,向量大小将高达10000,效率很重要,复制过程会带来问题吗? - caesar
3
不比其他任何事情更重要。时间的最大部分可能是1)IO本身,然后是2)转换为文本。对于其余部分,复制将几乎执行您在循环中执行的操作。 - James Kanze

4

使用反向迭代器:

for (std::vector<int>::reverse_iterator it = myvector.rbegin(); it != myvector.rend(); ++it)

或者在您的代码中,从 size() - 1 开始 for 循环:
for(int i=temp.size()-1;i>=0;i--) 

替代而非
for(int i=temp.size();i>=0;i--)

我认为你的意思是reverse_iterator,它带有rbegin()和rend()。 - Yochai Timmer

0
std::copy(head_buff.rbegin(), head_buff.rend(),
          std::ostream_iterator<std::string>(data_pack, "\n"));

但使用 #include<fstram>#include<iterator> #include<osstream> 第二种方法是遍历整个向量并将内容复制到字符串中 然后将字符串写入 ofstream 即

std::string somthing;
for(std::vector<std::string>::const_iterator i = temp.begin();i!=temp.end(); ++i)
 {
     something+=*i;
 }

然后将字符串(something)写入 ofstream,即:

std::ofstram output;
output.open("test.txt",std::ios_base::trunc)
if(output.fail())
  std::cerr<<"unable to open the file"std::endl;
output << something;
//after writing close file
 output.close();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接