Filling array of arrays

Viewed 53

I am trying to calculate the correlation and store the values in an array of arrays. It seems like the problem is filling vectors into a vector. I have tried some solutions but no luck. I appreciate your help.

void BuildCorrelationForMatrix()
{
std::vector<std::unique_ptr<correlation>> m_correlationMatrix;
std::vector<std::vector<float>> m_correlationValues;
std::vector<float> row_values;
float value_inrow ;

for(int col_idx = 0; col_idx < (int) m_correlationData.size(); ++col_idx){
  for(int col_idy = 0; col_idy < (int) m_correlationData.size();++col_idy){
            
  auto data1= m_correlationData[col_idx];  
  auto data2= m_correlationData[col_idy];
                              
  m_correlationMatrix.push_back(std::make_unique<correlation>(data1, data2);
            
  value_inrow = m_correlationMatrix[col_idy]->CalculateCorrelation();
  row_values.push_back(value_inrow);

  // m_correlationValues[col_idx][col_idy]=value_inrow; //not works
    }

  m_correlationValues[col_idx].push_back(row_values); // problem is here!
 //m_correlationValues[col_idx]=row_values; // not works
                       
 }
}
1 Answers
std::vector<std::vector<float>> m_correlationValues;

This creates a new vector. This vector is completely empty. There's nothing in it.

 m_correlationValues[col_idx].push_back(row_values);

The [] operator accesses existing values in the vector. It does not add values to a vector. It doesn't matter what col_idx is, here. This is accessing non-existent index in a vector, which is undefined behavior and the reason for your crash.

Note that for the 2nd level in this two-dimensional vector the shown code correctly uses push_back to add values to the 2nd dimension of this vector.

Observe that col_idx iterates between 0 and m_correlationData.size()-1, according to the outer for loop. Therefore, it should be possible to fix this crash simply by adding

m_correctionValues.resize(m_correlationData.size());

at the beginning of this function.

Related