我正在尝试将矢量分成n个部分。 我检查了以下解决方案How to split a vector into n "almost equal" parts
我根据以下评论推出了以下代码: 要获得每个零件尺寸的基数,只需将总数除以零件数量:11/3 = 3.显然,某些零件需要大于该零件才能得到合适的零件,但是那就是余数:11%3 = 2.所以现在你知道其中2个部分的大小是3 + 1,剩下的就是3.(Mark Ransom)
int main()
{
std::vector<int> lines;
int size = 200;
for(int i = 0; i < size;i++)
{
lines.push_back(i);
}
int p = 6;
int right = round((double)size/(double)p);
for(int i = 0; i < p;i++)
{
if( i < size - left)
{
vector<int> v;
for(int j = 0; j < right; j++)
{
v.push_back(lines[j]);
}
cout << v.size() << endl;
}
else if (i > size - left)
{
vector<int> v;
for(int k = 0; k < right; k++)
{
v.push_back(lines[k]);
}
cout << v.size() << endl;
}
}
return 0;
}
p = 6且尺寸= 200的输出为:33,33,33,33,33,33 = 198
p = 6且size = 1000的输出为:167,167,167,167,167,167 = 1002
两个输出都是错误的。我错过了什么?
编辑后:
所以让我明白一下。 我们通过右增加 i ,它表示块或子矢量的大小。 虽然我小于尺寸 - 右但我们什么都不做。当我变得更大时,我们必须处理剩余物,我们通过 right = size - i 来改变块的大小。
int main()
{
std::vector<int> lines;
int size = 1000;
for(int i = 0; i < size;i++)
{
lines.push_back(i);
}
int p = 6;
int right = round((double)size/(double)p);
int left = size % p;
for(int i = 0; i < size; i+= right)
{
if(i < size - right)
{
vector<int> v;
//MAJOR CORRECTION
for(int j = i; j < (i+right); j++)
{
v.push_back(lines[j]);
}
cout << v.size() << endl;
}
else
{
right = size - i;
vector<int> v;
//Major Correction
for(int k =i; k < size; k++)
{
v.push_back(lines[k]);
}
cout << v.size() << endl;
}
return 0;
}
输出:33 33 33 33 33 33 2 = 200
答案 0 :(得分:1)
int right = size/p; // don't round! this floors.
int left = size % p; // this one is correct.
for(int i = 0; i < p;i++)
{
if( i < size - left)
{
vector<int> v;
for(int j = 0; j < right; j++) // counters, you used i here.
{
v.push_back(lines[j]); // and here.
}
cout << v.size() << endl;
}
else if (i >= size - left)// sorry equal is here. try >= not > , comment with results.
{
vector<int> v;
for(int j = 0; j < right+1; j++) // and here
{
v.push_back(lines[j]); // and here
}
cout << v.size() << endl;
}
}
答案 1 :(得分:0)
以其他方式思考你的想法:
p (parts) = 3, size = 11, ceil(11/3) = 4
所以4 + 4 + 3 = 11
其他相同
p = 6, size = 200 ceil(200/6) = 34
所以,34 + 34 + 34 + 34 + 34 + 30 = 200
int p = 6;
size_t nLimit = ceil((double)lines.size()/p);
// if you don't want to contain the leftover element within p elements, use floor
vector<int>::iterator start = lines.begin();
for(size_t i = 0; i < lines.size(); i+=nLimit){
// Just use the constructor/insert function
vector<int> v(start+i, start+std::min<size_t>(i+nLimit, lines.size()));
cout<<v.size()<<endl;
}
这里的工作代码: http://ideone.com/6V7rSX