我有这个程序用浮点值填充向量,确保当浮点值总计时每个向量(bin)的总和小于1.0。我通过调试发现程序在尝试将向量的值添加到浮点时停止。原因是因为for循环运行的次数比向量中存在的元素多。我插入一个cout来检查大小的值,并得到一个非常大的数字(9500万的东西)
//Bin packing algorithm
//Takes float values which are <1 and packs them into bins.
#include <iostream>
#include <vector>
#include <list>
#include <cassert>
using namespace std;
typedef unsigned int uint;
bool gt( float a, float b )
{
return b < a;
}
int main()
{
list< float > S;
while( ! cin.eof() )
{
float value;
if( cin >> value && ! cin.eof() )
{
assert( value > 0.0 && value <= 1.0 );
S.push_back( value );
}
}
uint n = S.size();
uint operations = 0;
vector< vector< float > > bins;
S.sort( gt );
float currentitem;
float binsum;
uint totalbins = 0;
uint currentbin;
vector<float> tempbin;
while(S.size() != 0)
{
currentitem = S.front();
S.pop_front();
currentbin = 0;
while(currentitem != 0 && totalbins > currentbin)
{
currentbin++;
bintotal = 0;
for(uint i=0; i < bins[currentbin].size(); i++)
{
cout << "i=" << i <<" bins[currentbin].size()=" << bins[currentbin].size() << endl;
binsum += bins[currentbin][i]; //THIS IS WHERE THE DEBUGGER POINTS. bins[currentbin].size() is producing the 95 million garbage value.
}
if((binsum + currentitem) <= 1)
{
currentitem = 0;
bins[currentbin].push_back(currentitem);
}
}
if(currentitem != 0)
{
totalbins++;
tempbin.push_back(currentitem);
bins.push_back(tempbin);
tempbin.clear();
}
}
答案 0 :(得分:2)
bins[currentbin]
循环访问无效bin中的 for
currentbin
变量已经递增。在currentbin++
循环后,您需要for
。