Abdalah El-Barrad
Abdalah El-Barrad

Reputation: 471

Vector size not increasing as variable is added

I have the following script that creates all possible points in a specific base:

int main(){

  int base;
  cout << "Enter Base: ";
  cin >> base;

  int dimension;
  cout << "Enter Dimension: ";
  cin >> dimension;

  //This creates all possible numbers
  vector<double> dist;
  dist.reserve(base);
  for(int k=0; k<base; k++){
    dist[k] = (-1.0+k*2.0/(base-1.0));
  }

  vector< vector<double> > points;
  int perms = 1;
  for(int i=0; i<dimension; i++){
    perms *= base;
  } // base^dimension
  points.reserve(perms);

  vector<double> stand;
  stand.reserve(dimension);

  // Defined later
  getPermutations(dist, base, stand, dimension, 0, points);

  for(int i=0; i<points.size(); i++){ //DOESN'T DO ANYTHING BECAUSE SIZE IS 0
    cout << '(';
    for(int j=0; j<points[i].size(); j++){
      cout << points[i][j] << ',';
    }
    cout << ')' << endl;
  }

  return 0;
}

It won't do anything because the size function only increases when I use the push_back() function instead of indexing. I have to use indexing because of the permutations function below:

void getPermutations(vector<double>& arr, int size,
                     vector<double>& data,int dimension,
                     int index, vector< vector<double> >& combs){
  int i;
  //stop recursion condition
  if(index == dimension){
    combs.push_back(data);
  }
  else{
    for(i = 0; i < size; i++){
      data.at(index) = arr.at(i);
      getPermutations(arr, size,data,
                      dimension,index+1, combs);
    }
  }
}

I don't understand why the vector sizes are zero and errors keep popping up saying:

terminate called after throwing an instance of 'std::out_of_range'
  what():  vector::_M_range_check: __n (which is 0) >= this->size() (which is 0)

Upvotes: 3

Views: 1543

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409166

The std::vector::reserve function doesn't do what you think it does. It doesn't change the size, just the capacity (the amount of memory allocated for the vector).

That means when you create e.g. the dist vector and directly after calling reserve you have a loop and do

dist[k] = (-1.0+k*2.0/(base-1.0));

you are actually indexing out of bounds and have undefined behavior.

The solution is to actually set the size. Either through std::vector::resize, or simply setting the size when creating the vector:

std::vector<double> dist(base);  // Creates vector with a specific size

You have the same problem with all your vectors, and all of them needs to change accordingly.

Upvotes: 8

Related Questions