Accessing vector<vector<char> > elements as rows and columns
I am trying to use a
vector<vector<char> > matrix;
as an actual matrix.
matrix is initialized with all '\0' and it gets filled in during the process.
let's imagine at a certain point of time I am in this situation:
0 1 2 3
0 a b c \0
1 b b \0 \0
2 c \0 \0 \0
3 \0 \0 \0 \0
if I want to have a char * to the first row I can do a:
&word_square[0][0]
that will give me a pointer to the first row, pointer that I can use as a C char array (ie. "abc")
What if I want to get the first column in the same way? Is it possible or I'll have to do it with a for?
int i =0;
string column;
while(matrix[i][0] 开发者_如何学运维!= '\0' )
{
column.push_back(matrix[i][0]);
i++;
}
I would love to get a cleaner solution as I did above for the row. initializing a string just for getting the column I need and I already have it's not so nice. Moreover it slows down my process.
Many thanks to those who will help.
Using a vector< vector<char> >
, you have no guarantee that the inner vectors store their data contiguously in memory, meaning there is no possible way to have a char*
that points to the elements in column order unless you manually copy the data.
You can slice a std::valarray to do something along the lines of what you're interested in doing. They use contiguous memory, and the slice manages access to the original data object, so there's no copying involved.
Impossible with a vector of vectors. Your best bet is to write your own class that returns proxy objects.
精彩评论