Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

2D vector with aligned allocator syntax problem

I am completely stuck when I am trying to put the value of 2D vector into another 2D vector. The code execution just exit. Putting a little extra code to make things more clear.

int data_size_val= 8;
int n_qubits_val = ceil(log2(data_size_val));
int n_states_val = pow(2, n_qubits_val);
vector<vector<float, aligned_allocator<float> >> source_phi;

vector<vector<float>> phi_val;

for(int i=0;i< n_states_val/2;i++){
vector<float> temp;
for(int j=0;j< n_qubits_val;j++){
temp.push_back(0);
}
phi_val.push_back(temp);
}
 for(int i=0;i< n_states_val/2;i++){
    for(int j=0;j< n_qubits_val;j++){
    source_phi[i][j]= phi_val[i][j];           // This is where Code Exit execution
    }
 }

It would be really great if I can be helped to resolve this issue. I think, there is some problem with syntax of 2D vector "source_phi".

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Your source_phi is an empty vector of empty vectors. So, the source_phi[i][j]= phi_val[i][j] assignment is attempting to assign a value to a non-existent element of a non-existent vector.

There are several ways you can handle this. One is to use the push_back and temp approach that you used when initialising the phi_val vector in the first set of nested for loops:

    //...
    for (int i = 0; i < n_states_val / 2; i++) {
        vector<float, aligned_allocator<float>> temp; // Create empty temporary...
        for (int j = 0; j < n_qubits_val; j++) {
            temp.push_back(phi_val[i][j]); // Push data into the temporary
        }
        source_phi.push_back(temp); // Now push that temp into the outer vector
    }

An alternative (and likely more efficient) approach is to call the .resize() member function on: (1) the outer vector (before the outer for loop) and (2) on the inner vectors, on each run through that loop (before the inner loop):

    source_phi.resize(n_states_val / 2); // Allocates space for each vector
    for (int i = 0; i < n_states_val / 2; i++) {
        source_phi[i].resize(n_qubits_val); // Allocates space for each element
        for (int j = 0; j < n_qubits_val; j++) {
            source_phi[i][j] = phi_val[i][j]; // The LHS now exists and can be assigned
        }
    }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading