![](/img/trans.png)
[英]C++: Constructing a std::vector<std::vector<int> > with a two-dimensional C-array?
[英]Can I use std::vector<std::vector<T>> to represent two dimensional arrays in C++?
我最近学习了如何使用指针在普通C语言中处理二维和三维数组,但是,作为一名C ++爱好者,我还想弄清楚如何在C ++中处理多维数组。
我知道在C ++中做一维数组的首选方法是使用std::vector<T>
,但是二维数组和三维数组呢? 它们将被表示为std::vector<std::vector<T>>
和std::vector<std::vector<std::vector<T>>>
吗?
尽管可以从技术上做到这一点,但最好使用单个std::vector<T>
并手动计算偏移量。 最终的内存布局将对缓存更加友好,因为所有内容都将紧密地打包在一起,并且可以顺序遍历或无间接索引。
但是,如果C ++ 11是一个选项,并且数组的大小在编译时是固定的,则应使用嵌套的std::array
。 使用std::unique_ptr
可以轻松实现动态分配。 但是请注意,数据不一定在子数组之间严格相邻,这在与API期望单个ol'数据块接口时可能会出现问题。
当然,您可以使用类std :: vector来模拟数组。 例如
#include <iostream>
#include <vector>
int main()
{
size_t n;
size_t m;
std::cout << "Enter the number of rows: ";
std::cin >> n;
std::cout << "Enter the number of columns: ";
std::cin >> m;
std::vector<std::vector<int>> v( n, std::vector<int>( m ) );
return 0;
}
当列数是编译时间常数时,也请考虑使用std :: vector与std :: array的组合。
例如,所谓的3维数组的定义看起来像
std::vector<std::vector<std::vector<int>>>
v( 2, std::vector<std::vector<int>>( 3, std::vector<int>( 4 ) ) );
一个更有趣的例子
#include <iostream>
#include <vector>
#include <numeric>
int main()
{
size_t n;
size_t m;
std::cout << "Enter the number of rows: ";
std::cin >> n;
std::cout << "Enter the number of columns: ";
std::cin >> m;
std::vector<std::vector<int>> v( n, std::vector<int>( m ) );
for ( size_t i = 0; i < n; i++ )
{
std::iota( v[i].begin(), v[i].end(), i * m );
}
for ( const auto &v1 : v )
{
for ( auto x : v1 ) std::cout << x << ' ';
std::cout << std::endl;
}
return 0;
}
如果分别为n和m输入3和5,则输出为
0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
当然!
#include <vector>
#include <iostream>
int main()
{
typedef std::vector<double> VD;
typedef std::vector<VD> VVD;
// 10x5 matrix filled with ones
VVD mtx(10, VD(5, 1));
std::cout << mtx.size() << " " << mtx[0].size() << std::endl;
std::cout << mtx[3][2] << std::endl;
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.