简体   繁体   中英

Dereferencing not working for std::vector<std::vector<double> >

struct myS {
   std::vector<std::vector<double> > *A;
}

I want to access the elements of A using indices. I tried this (and also other versions) but it did not work.

struct myS test;   
std::vector<double> B = *(test.A)[0];

重新放置支架:

std::vector<double> B = (*test.A)[0];

This compiles:

struct myS{
   std::vector<std::vector<double> > *A;
};
myS instanceOfMyS;

std::vector<double> B = (*instanceOfMyS.A)[0];

Note

  • struct myS just declares a type of myS . To declare an instance of the type you need to add the instanceOfMyS afterwords.
  • You also omitted the <double> in the declaration of B .

However the code above will take a copy of the first element in *instanceOfMyS.A . So you might want a reference instead.

std::vector<double>& B = (*instanceOfMyS.A)[0];

Finally, it looks a bit dodgy that you're using a pointer in your struct (with a pointer you don't allocate the memory to back the vector pointed to be A unless you explicitly allocate the memory, leading to access violations). You might want the following

struct myS{
   std::vector<std::vector<double> > A;
};
myS instanceOfMyS;

std::vector<double>& B = instanceOfMyS.A[0];

This will work :

myS myObj;
// Add some stuff in your vector(s) ...
...
// Access your vector
std::vector<double> B = (*myObj.A)[0]; // Don't forget here that it will copy the elements of the vector

Or if you want to access to an item into the second vector :

double B = (*myS.A)[0][0];

Another question : Why are you using a vector in the structure in this case ? In my own opinion, you should not have this pointer in your struct. It should be a value like :

struct myS{
   std::vector<std::vector<double> > A;
}

EDIT : small mistakes on dereferencing pointer resolved

You should write (myS->A)[i] to access the ith outer vector: rewrite your line as

std::vector B = (myS->A)[0] ;

but note that this will take a value copy of the vector.

By the way, you will need to do (myS->A)[i][j] to access the jth element in the ith outer vector,

But why use a pointer in the first place?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM