从矢量数组制作平面文件

Making a flat file from vector array

我的计划是制作一个分为两列的平面文件,为此我启动了两个向量数组。两个向量数组将位于平面文件的两列中。我认为我遇到的问题是在平面文件的列中填充矢量元素。我是不是填错了?

outFile << vec1[i] << "\t" << vec2[i] << endl;

  #include <fstream>
#include <vector>

using namespace std;
//int main()
void ffile()
{
    std::ofstream ofs;
    ofstream outFile;
    outFile.open("flatFile.dat");
     vector<int> vec1{ 10, 20 };
     vector<int> vec2{ 0, 20, 30 };


    for (int i=0; i<=3;i++)

{
  outFile << vec1[i] << "\t" << vec2[i] << endl;
    }
}

更新问题: 我有两个向量大小不同的向量。如果我使用 size the large vector 运行 代码会有什么问题吗?

另一件事是,在平面文件中我没有看到两列,而是只看到一列和来自向量 vec2[i] 的条目。如何让 vec1 的第一列和 vec2 的第二列都有这两个条目?

C++ 不允许从向量中读取超过其最后一个元素的内容。句号。如果您使用 at 方法,您将得到一个 out_of_range 异常,而使用 [] 运算符您只会遇到未定义的行为。

这意味着您必须检查向量的大小。您的代码可能会变成:

#include <fstream>
#include <vector>
#include <algorithm>

using namespace std;
//int main()
void ffile()
{
    // std::ofstream ofs;     // unused 
    ofstream outFile;
    outFile.open("flatFile.dat");
    vector<int> vec1{ 10, 20 };
    vector<int> vec2{ 0, 20, 30 };

    // use the sizes of both vectors to compute the loop limit
    for (unsigned i = 0; i <= std::max(vec1.size(), vec2.size()); i++)

    {
        if (i < vec1.size()) outFile << vec1[i];  // only output actual values
        outFile << "\t";
        if (i < vec2.size()) outFile << vec2[i];
        outFile << endl;
    }
}

此代码应提供类似于以下内容的文本文件:

0   0
20  20
    30

(它在我的测试中...)