我有这个程序用浮点值填充向量,确保当浮点值总计时每个向量(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();
}
}