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

writing content of vector to file c++

本文关键字:文件 C++ 向量      更新时间:2023-10-16

我试图将我的矢量内容写入文件。为此,我编写了一段代码,如下所示:

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";
}

当我写这篇文章时,我可以轻松地做我想做的事。 文件的内容是:

123

但是,当我想从反向将我的矢量写入文件时(如下所示)。我一无所获。只是空文件。有人可以帮助我吗?提前谢谢。

for(int i=temp.size()-1;i>=0;i--)
    outputfile<<temp[i]<<"n";
您可以使用

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";

使用 VS12 在我的窗户上工作正常。

您可以在 1 行中完成所有操作:

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

使用反向迭代器:

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--)
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;
 }

然后将字符串(某些东西)写入 Ofstream IE

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();