[英]How to split vector into subsets?
我試圖根據我在應用程序中使用的進程數將向量拆分為子集。 我創建了偽代碼,但我真的不知道如何輸出子集。
問題:
使用條帶化從Residences.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()){ResidenceFile >> res.x >> res.y;
if ( numLines % numProcs == rank)
{
//call the process
//populate_distancesVector(res,foodbankData);
analysis_range(populate_distancesVector(res,foodbankData),count);
}
++numLines;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.