I know that the standard does not force std::vector
to allocate contiguous memory blocks, but all implementations obey this nevertheless.
Suppo
As @Als already pointed out, yes, std::vector
(now) guarantees contiguous allocation. I would not, however, simulate a 2D matrix with an array of pointers. Instead, I'd recommend one of two approaches. The simpler by (by far) is to just use operator()
for subscripting, and do a multiplication to convert the 2D input to a linear address in your vector:
template
class matrix2D {
std::vector data;
int columns;
public:
T &operator()(int x, int y) {
return data[y * columns + x];
}
matrix2D(int x, int y) : data(x*y), columns(x) {}
};
If, for whatever reason, you want to use matrix[a][b]
style addressing, you can use a proxy class to handle the conversion. Though it was for a 3D matrix instead of 2D, I posted a demonstration of this technique in previous answer.