How to get a pointer to the contents of 2D std :: vector

Considering

std::vector<char> theVec 

I can get the pointer as follows

 char* cc = &theVec[0] 

What if the vector is declared as follows:

 std::vector<std::vector<char> > theVec 

How do you get a pointer to a Vec head on char *

 char cc* = 
+4
source share
2 answers

How do you get a pointer to the Vec head [like char *]?

You can not. The head of your vector is of type std::vector<char> , not char , and std::vector<std::vector<char> > does not store its data in one continuous block.

Instead, you can do this:

 std::vector<char> theVec; theVec.resize(xSize*ySize); char cc* = &theVec[0]; char tmp = theVec[x*xSize + y];//instead of theVec[x][y] 
+4
source
 std::vector<char> * p = &theVec[0]; 

If you want a pointer to the first char, then:

 char * p = &theVec[0][0]; 

However, be careful, because repeating this pointer past the first subvector will not lead it to the next vector, as would happen with a multidimensional array. To get a pointer to the header of the following sub-vector, you should use:

 p = &theVec[1][0]; 
+2
source

All Articles