c++ - 将 ifstream 拆分为 n 个流?

标签 c++ stream ifstream istream seekg

我的 ifstream 有问题。我想将 ifstream 分成 n 个部分。

例如 n = 3:

  1. Ifstream 包含文件的前 1/3。
  2. Ifstream 包含文件的第二个 1/3。
  3. Ifstream 包含文件的第三个 1/3。
    std::ifstream in("test.txt");
    std::vector<std::string> v1;
    std::vector<std::string> v2;
    std::vector<std::string> v3;

    //first 1/3 of file
    read(in, v1);
    //second 1/3 of file
    read(in, v2);
    //third 1/3 of file
    read(in, v3);

    read(in, v){

         std::string line {""};
         while(getline(in, line)){
              v.pushback(line);
         }
    }

最佳答案

您可以读取并推送 vector 中的所有行,然后将 vector 分成 3 部分,例如:

std::string s;
while(!in.eof() && getline(in, s)) v1.push_back(s);
int size = v1.size(), itv2 = 0, itv3 = 0, chunk = v1.size()/3;
for(unsigned i = size-1; i >= size/3; --i, v1.pop_back()) 
    (i > chunk*2)? v3[chunk-itv3++] = v1[i] : v2[chunk-itv2++] = v1[i]; 

现在,如果您想对 n 个分区执行此操作,您可以执行类似的操作:

//n must be defined before use
std::vector<std::vector<std::string> > vChunks(n+1);
std::vector<std::string> v;
std::string s;
while(!in.eof() && getline(in, s)) v.push_back(s);
int size = v.size(), chunk = v.size()/n, r = v.size()%n;
vChunks[n].resize(r);
for(int i = 0; i < n; i++)
    vChunks[i].resize(chunk);
for(int i = v.size()-1, it =1; it <= r; it++, --i, v.pop_back())
    vChunks[n][r-it] = v[i];
for(int i = v.size()-1; i >= 0; --i, v.pop_back())
    vChunks[(i%chunk == 0)? (i-1)/chunk : i/chunk][i%chunk] = v[i];

其中,vChunks 的前 n 个分区具有 n 个维度之间的行数,并且在 n + 1 中,如果不能被 n 整除,则最后几行的其余部分具有行数

关于c++ - 将 ifstream 拆分为 n 个流?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60114833/

相关文章:

c++ - 比较列表并给出列表 b 中不在列表 a 中的内容

c++ - 您可以将 shared_ptr 用于 C 样式数组的 RAII 吗?

f# - 如何正确关闭流?

javascript - 无法正确编码前置记录器

javascript - 如何在网页上流式传输(分段)mp4 视频

c++ mysql连接器检查结果集为空

c++ - 如何使用(模板)迭代器值创建一个集合?

c++ - 如何检查 ifstream 文件末尾是否有新行。 (c++)

c++ - 读取文本文件导致缓冲区末尾出现无效字符

c++11 - ifstream 检查读取错误