如何创建std :: ofstream的向量并将流写入不同的文本文件

问题描述 投票:1回答:1

我只是尝试使用std::vectorstd::ofstream向一些不同的文件中写入一些数字。我的程序正在编译并运行,并且正在生成文件,但是我的文件中没有文本。

#include <iostream>
#include <fstream>
#include <vector>

int main()
{

    auto num_components = 3;
    std::vector<std::ofstream> files_to_be_written;
    files_to_be_written.resize(num_components);

    for (auto i = 0; i < num_components; ++i){
      std::string file_name = "text" + std::to_string(i) + ".txt";
      files_to_be_written.emplace_back(std::ofstream{ file_name });
    }

    std::vector<std::vector<int>> data_to_be_written;
    data_to_be_written.resize(num_components);
    data_to_be_written[0].push_back(1);
    data_to_be_written[0].push_back(2);
    data_to_be_written[0].push_back(3);
    data_to_be_written[1].push_back(4);
    data_to_be_written[1].push_back(5);
    data_to_be_written[1].push_back(6);
    data_to_be_written[2].push_back(7);
    data_to_be_written[2].push_back(8);

    for (auto& it : data_to_be_written)
    {
        auto idx = &it - &data_to_be_written[0];
        for (auto i = it.begin(); i != it.end(); ++i)
        {
            files_to_be_written[idx] << *i << "\n";
        }
    }

    for (auto i = 0; i < num_components; ++i){
        files_to_be_written[i].close();
    }
}

我不确定我在哪里犯错。

c++ stringstream
1个回答
1
投票
auto num_components = 3;
std::vector<std::ofstream> files_to_be_written;
files_to_be_written.resize(num_components);

由于在这里调用std::vector::resize(),因此将在向量中创建三个新的空std::ofstream元素。然后,使用文件路径将另外三个std::ofstream对象附加到带有std::vector::emplace_back()的向量的后面。您最终在向量中包含6个元素。

问题是,您仅在这段代码中只写了前三个std::ofstream元素:

for (auto& it : data_to_be_written)
{
    auto idx = &it - &data_to_be_written[0];
    for (auto i = it.begin(); i != it.end(); ++i)
    {
        files_to_be_written[idx] << *i << "\n";
    }
}

解决方案很简单。替换

files_to_be_written.resize(num_components);

with

files_to_be_written.reserve(num_components);

std::vector::reserve()不会在向量中添加任何新元素,而只是为其分配内存。

© www.soinside.com 2019 - 2024. All rights reserved.