Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vector <vector <double>> operator

Tags:

c++

I want to modify a

vector <vector <double>>

declared in main() from another function.
I pass the pointer to the vector as a function parameter; unfortunately, as soon as I try to modify the vector I get a segmentation error.

Originally this was my code:

#include <vector>
#include <iostream>

using namespace std;
void function(vector <vector <double>> *result, int k){
    double r = 0.2;
    for(int i=0;i<5;i++){
        r = r*0.2;
        result[k][i].push_back(r);
    }
}

int main(){
    vector <vector <double>> result;
    for(int i=0;i<5;i++) function(&result, i);

    for(int i=0;i<5;i++){
        for(int j=0;j<5;j++) cout << result[i][j] << " ";
        cout << " " << endl;
    }
    return 0;
}

The compilation with "g++" went good but I got segmentation error when I ran the program.
I think the problem is in the use of the operator [] since I am applying it to a pointer, so I might need something like:

result->operator[](k)->operator[](i).push_back(r);

which I tried but unfortunately doesn't compile.

EDIT: I was using "push_back()" on result[k][i] which is a double.

I modified:

result[k][i].push_back(r);

in:

res[k][i]=r;

but I still get a segmentation error :/

EDIT 2: The problem was in the declaration of the vector of vectors; I didn't specify a size. It should look like:

vector <vector <double>> result(int size);
like image 856
LucioPhys Avatar asked Apr 16 '26 11:04

LucioPhys


1 Answers

Just pass the vector by reference:

//                     -------------v
void function(vector<vector<double>>& res, int k){
    //some calculations
    for(int i=0;i<5;i++){
        //calculations which give r (double) as result
        res[k].push_back(r);
    }
}

If you really want to pass it by pointer, then you have to dereference it:

void function(vector<vector<double>>* res, int k){
    //some calculations
    for(int i=0;i<5;i++){
        //calculations which give r (double) as result
        (*res)[k].push_back(r);
    }
}

And as @gambinaattori says, you cannot push back into a double, you push back into the vector in the outermost vector.

You'll also need to first vector to be filled with vectors. If the first level of vector is empty, you cannot push back the second level since there is none.

Initializing the vector of vector with a bunct of empty vectors in it is done like that:

std::vector<std::vector<double>> result(5);

Now there is 5 empty vectors.

Then to pass by reference you need drop the & symbol from the arguments:

function(result, i);

Here's a live example.

like image 193
Guillaume Racicot Avatar answered Apr 18 '26 01:04

Guillaume Racicot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!