gpt4 book ai didi

c++ - 如何将 vector 拆分成子集?

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:25:32 31 4
gpt4 key购买 nike

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

问题:

Read a subset of the address records from residences.dat using striping. For n processes, each process evaluates a unique subset of records based on every nth record. The number of records in this subset should be approximately #-of-residence-records /#-of-processes. Across all the parallel processes used no address should be omitted and none should be processed more than once. Also note that only ONE record at a time should be stored in memory by any process

我的代码:

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

最佳答案

我还没有测试过这段代码,但是与此类似的东西应该可以工作——不是让你的函数返回一个 vector ,而是让它返回一个 vector 的 vector ,就像这样:

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

这将允许您将原始 vector 拆分为 num_procs vector 数,然后是 push_back()每一个都到你的 vector 的返回 vector (有点像矩阵)。

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

这将允许您获得这样的子 vector :

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

关于c++ - 如何将 vector 拆分成子集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19897208/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com