Reputation: 317
I have this program which fills a vectors with float values, ensuring each vector (bin) has less than a sum of 1.0 when the float values are totaled. I discovered through debugging that the program is halting when it tries to add values of a vector to a float. The reason is because the for loop is running more times than elements that exist in the vector. I inserted a cout to check the value of the size, and am getting a very large number (95 million something)
//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();
}
}
Upvotes: 2
Views: 4205
Reputation: 11232
bins[currentbin]
in the for
loop access invalid bin as currentbin
variable is already incremented. You need to currentbin++
after the for
loop.
Upvotes: 3