dimanche 12 septembre 2021

Question About Vector Initialization (C++)

I was writing some code to compute the longest subsequence of a given vector of type int. With that said, I came across an issue that I fixed but not really sure what the underlying difference is between the fix and my original solution.

Context

@parameters
 -- const vector<int> &data

vector<vector<int>> arr;
/** Initialize the Dynamic Array **/
for(int row = 0; row < data.size(); row++){
  <line_in_question>
  entry[0]=1;
  arr.push_back(entry);
}

//do something with arr

Original

vector<int> entry(data.size(), 0);

Fix

vector<int> entry = vector<int>(data.size(), 0);

Error Message

error: terminating with uncaught exception of type std::out_of_range: vector

I'm thinking the difference just comes down to how memory is allocated but still not sure how exactly. Thanks!

Aucun commentaire:

Enregistrer un commentaire