[英]Does std::array of std::array have contiguous memory?
Seems, that I found how to easily get normal 2D Array with contiguous memory in 2 lines of code: 似乎,我发现如何用两行代码轻松获得具有连续内存的普通2D数组:
template<int N, int M>
using Array2D = array<array<int, M>, N>;
Let's solve easy task of swapping min and max in Array2D
(a little of c++17): 让我们解决在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;
}
}
I got next result in Visual Studio 2017: 我在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
Pros: 优点:
arr[2][2]
您通常可以将元素访问为arr[2][2]
Cons: 缺点:
array iterators incompatible
该解决方案在调试模式下无法正常工作,我的运行时错误array iterators incompatible
Questions: 问题:
Array2D
ensured by anything? 是否Array2D
确保Array2D
连续分配? Array2D
safe to use in this manner (as in example) in production code? 以这种方式(例如)在生产代码中使用Array2D
是否安全? If not, can you present good code for solving this task with minimum code overhead? 如果不是,您能否以最小的代码开销提供良好的代码来解决此任务? According to the standard the memory should be contiguous. 根据标准,内存应该是连续的。 The 26.3.7.1 [array.overview] paragraph states (emphasis mine): 26.3.7.1 [array.overview]段落指出(强调我的意思):
The header defines a class template for storing fixed-size sequences of objects. 标头定义用于存储固定大小的对象序列的类模板。 An array is a contiguous container . 数组是一个连续的容器 。 An instance of array stores N elements of type T, so that size() == N is an invariant. 数组的实例存储N个类型为T的元素,因此size()== N是不变量。
Update: It appears the implementation might include the padding. 更新:看来实现可能包括填充。 More info on the subject in these SO posts: 这些SO帖子中提供了有关该主题的更多信息:
Is the size of std::array defined by standard? std :: array的大小是否由标准定义?
and specifically this answer: 特别是这个答案:
Is the data in nested std::arrays guaranteed to be contiguous? 嵌套std :: arrays中的数据是否保证是连续的?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.