最近,我学习了如何使用指针在普通C中实现二维和三维数组,但是作为一个C++爱好者,我也想知道如何在C++中实现多维数组。
我知道在C++中进行一维数组的首选方法是使用std::vector<T>,但是二维和三维数组呢?它们会被表示为std::vector<std::vector<T>>和std::vector<std::vector<std::vector<T>>>吗?
发布于 2014-07-23 20:29:17
当然,您可以使用类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的组合。
例如,所谓的三维数组的定义可以看上去像这样。
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 发布于 2014-07-23 20:26:05
虽然您可以在技术上做到这一点,但是使用单个std::vector<T>并手工计算偏移量是一个更好的主意。由此产生的内存布局将更加易于缓存,因为所有的东西都将紧密地打包在一起,并且可以按顺序遍历,或者没有间接的索引。
但是,如果C++11是一个选项,并且您的数组的大小在编译时是固定的,那么您应该使用嵌套的std::array。动态分配可以很容易地通过std::unique_ptr实现。但是,请注意,数据不一定是子数组之间严格连续的,这可能是一个问题,当与API的接口需要一个单一的ol‘’数据块。
发布于 2014-07-23 20:23:58
好的!
#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;
}https://stackoverflow.com/questions/24920191
复制相似问题