i'm trying to use iterators on a 3d matrix allocated dynamically.
matrix = new T**[height];
for(int i =0; i<height; i++){
matrix[i] = new T*[col];
for(int j =0; j<col; j++){
matrix[i][j] = new T[row];
}
}
Is it possible to iterate over this matrix using iterators? Or is better to choose a different solution using iterators? (no vector solution)
If it's possible, how can I implement them?
Every pointer meets the criteria for an iterator, too. So you can iterate as follows:
for(T*** begin1 = matrix, end1 = matrix + height; begin1 != end1; ++begin1)
{
for(T** begin2 = *begin1, end2 = *begin1 + col; begin2 != end2; ++begin2)
{
for(T* begin3 = *begin2, end3 = *begin2 + row; begin3 != end3; ++begin3)
{
begin3->doSomething();
}
}
}
This works with standard library algorithms as well:
std::for_each
(
matrix, matrix + height, [](T** t)
{
std::for_each
(
t, t + col, [](T* t)
{
std::for_each
(
t, t + row, [](T& t)
{
t.doSomething();
}
);
}
);
}
);
Untested code, if you find a bug, please fix it yourself.
You are likely better off with std::vector
, though, this relieves you from all the manual memory management and additionally allows for much simpler construction:
std::vector<std::vector<std::vector<T>>> v
(
height, std::vector<std::vector<T>>(col, std::vector<T>(row)
);
If you do not need jagged arrays for whatever reason, you will get more efficient code if you place all the values into a one-dimensional array/vector and do the index calculations on your own, then [x][y][z]
corresponds to [(x * col + y) * row + z]
.
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.