MrP*_*rik 9 c++ memory arrays allocation matrix
似乎,我发现如何在2行代码中轻松获得具有连续内存的普通2D数组:
template<int N, int M>
using Array2D = array<array<int, M>, N>;
Run Code Online (Sandbox Code Playgroud)
让我们来解决简单的任务交换最大和最小的Array2D(有点C++ 17):
template<int N, int M>
void printArray2D(const Array2D<N, M> &arr);
int main() {
const int N = 5;
const int M = 5;
Array2D<N, M> arr;
// random init of Array2D
generate(arr.front().begin(), arr.back().end(), []()->int {
return rand() % 100;
});
printArray2D(arr);
auto[a, b] = minmax_element(arr.front().begin(), arr.back().end());
cout << "Swap minimum and maximum: " << *a << " " << *b << endl << endl;
iter_swap(a, b);
printArray2D(arr);
return 0;
}
template<int N, int M>
void printArray2D(const Array2D<N, M> &arr) {
for (const auto &row : arr) {
for (const auto &elem : row) {
cout << std::setw(3) << elem;
}
cout << endl;
cout << endl;
}
}
Run Code Online (Sandbox Code Playgroud)
我在Visual Studio 2017中获得了下一个结果:
41 67 34 0 69
24 78 58 62 64
5 45 81 27 61
91 95 42 27 36
91 4 2 53 92
Swap minimum and maximum: 0 95
41 67 34 95 69
24 78 58 62 64
5 45 81 27 61
91 0 42 27 36
91 4 2 53 92
Run Code Online (Sandbox Code Playgroud)
优点:
arr[2][2]缺点:
array iterators incompatible问题:
根据标准,内存应该是连续的。26.3.7.1 [array.overview]段落指出(强调我的):
标头定义了用于存储固定大小的对象序列的类模板。数组是一个连续的容器。数组的实例存储 N 个 T 类型的元素,因此 size() == N 是一个不变量。
更新:看来实现可能包括填充。有关该主题的更多信息,请参阅这些 SO 帖子:
Is the size of std::array Defined by standard?
特别是这个答案:
嵌套 std::arrays 中的数据保证是连续的吗?
| 归档时间: |
|
| 查看次数: |
1174 次 |
| 最近记录: |