如何将向量拆分为子集

How to split vector into subsets?

本文关键字:子集 拆分 向量      更新时间:2023-10-16

我正在尝试根据我在应用程序中使用的进程数量将向量拆分为子集。我创建了伪代码,但我真的不知道如何输出子集。

问题:

从住宅读取地址记录的子集.dat使用 条带化。对于 n 个进程,每个进程计算 基于每 n 条记录的记录。此记录数 子集应大致为 #-居住记录/#-进程。在使用的所有并行进程中,不应省略任何地址,也不应多次处理任何地址。也 请注意,任何人一次只能将一条记录存储在内存中 过程

我的代码:

std::vector<Residence> spliteResidenceDaata(vector<Residence> rs,int numProces = 0);
function body 
    std::vector<Residence> spliteResidenceDaata(vector<Residence> rs,int numProces)
    {
        std::vector<Residence> residenceSet;
        //get the size of vector
        int res_set_size = rs.size();
        int sizrOfSubSet =res_set_size/numProces;
        //output the arry subsite some "help here"
        return residenceSet;
    }

更新

I came up with this pseudo code
1-take the number of line in .dat file  rData
2- get the number of data you want to read for each process sizeofLine  (rData.size()/numProc)
3- read the .dat file from line 0 to  sizeofLine
4-output array 

我还没有测试过这段代码,但是类似的东西应该可以工作 - 而不是让你的函数返回一个向量,让它返回一个向量向量,如下所示:

std::vector<std::vector<Residence>> split(std::vector<Residence rs, int num_procs)

这将允许您将原始向量拆分为num_procs个向量,然后将每个向量push_back()到向量的返回向量上(有点像矩阵)。

std::vector<std::vector<Residence>> split(const std::vector<Residence> rs, const unsigned num_procs) {
    unsigned j = 0; //position counter
    std::vector<std::vector<Residence>> result; //resulting vector of vectors
    for(unsigned i = 0; i < num_procs; ++i) {   //for each process
        std::vector<Residence> temp;            //create a vector
        for(; j < ((i + 1) * rs.size() / num_procs; ++j)    //iterate
            temp.push_back(rs[j]);              //and populate temporary vector with a 1/num_procs section of original vector
        result.push_back(temp);                 //and push that temporary vector into your result vector of vectors
    }
    for(; j < rs.size(); ++j)                   //finally, if the original vector is not divisible by num_procs
        result[num_procs].push_back(rs[j]);     //push the remainder of elements into the last vector
}

当你调用该函数时,它将看起来像这样:

std::vector<std::vector<Residence>> vectors = split(original_vector, 4);

这将允许您获得这样的子向量:

vectors[0];   //first quarter
vectors[1];   //second
vectors[2];   //third
vectors[3];   //fourth + remainder

您需要一次读取一条记录,而不是将所有子集作为向量传递,认为您需要这个 while(!residenceFile.eof()) { 住宅文件>> res.x>>res.y;

    if ( numLines % numProcs == rank)
    {
        //call the  process
        //populate_distancesVector(res,foodbankData);
        analysis_range(populate_distancesVector(res,foodbankData),count);
    }
    ++numLines;
}