开发者

How to get a pointer to a 2D std::vector's contents

开发者 https://www.devze.com 2023-03-21 06:03 出处:网络
Given std::vector<char> theVec I can get the pointer as follows char* cc = &theVec[0] What if the vector is declared as follows:

Given

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 the head of theVec into a char*

开发者_运维问答char cc* = 


How do you get a pointer to the head of theVec [as a char*]?

You can't. The head of your vector is of type std::vector<char>, not char, and a std::vector<std::vector<char> > doesn't store its data in one contiguous 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]


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 iterating that pointer past the first sub-vector will not move it into the next vector like would happen with a multidimensional array. To get a pointer to the head of the next sub-vector, you would use:

p = &theVec[1][0];
0

精彩评论

暂无评论...
验证码 换一张
取 消