如何在C/C++;? 是什么?(C)和/或C++中多维数组的动态(具有所有维度直到运行时未知)的公认的/最常用的方法。< /P>
我试图找到最干净的方法来完成这段Java代码的功能:如何在C/C++;? 是什么?(C)和/或C++中多维数组的动态(具有所有维度直到运行时未知)的公认的/最常用的方法。< /P>,c++,c,arrays,multidimensional-array,C++,C,Arrays,Multidimensional Array,我试图找到最干净的方法来完成这段Java代码的功能: public static void main(String[] args){ Scanner sc=new Scanner(System.in); int rows=sc.nextInt(); int cols=sc.nextInt(); int[][] data=new int[rows][cols]; manipulate(data); } public static void manipulate(int[][] data
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
int rows=sc.nextInt();
int cols=sc.nextInt();
int[][] data=new int[rows][cols];
manipulate(data);
}
public static void manipulate(int[][] data){
for(int i=0;i<data.length;i++)
for(int j=0;j<data[0].length.j++){
System.out.print(data[i][j]);
}
}
publicstaticvoidmain(字符串[]args){
扫描仪sc=新的扫描仪(System.in);
int rows=sc.nextInt();
int cols=sc.nextInt();
int[][]数据=新的int[行][cols];
操纵(数据);
}
公共静态无效操作(int[][]数据){
对于(int i=0;i),不能确定C++中给定数组的长度。最好的方法可能是通过数组中每个维度的长度,而不是使用数组本身的.FROM属性。 可以分配RoSsCLSSIEZOF(int),并通过表[Ro.CLS+Cal]访问它。 < P>使用<强> < /> > /<
在您的示例中,在编译时您只需要知道维度的数量。以下是文档中的第一个示例:
#include "boost/multi_array.hpp"
#include <cassert>
int
main () {
// Create a 3D array that is 3 x 4 x 2
typedef boost::multi_array<double, 3> array_type;
typedef array_type::index index;
array_type A(boost::extents[3][4][2]);
// Assign values to the elements
int values = 0;
for(index i = 0; i != 3; ++i)
for(index j = 0; j != 4; ++j)
for(index k = 0; k != 2; ++k)
A[i][j][k] = values++;
// Verify values
int verify = 0;
for(index i = 0; i != 3; ++i)
for(index j = 0; j != 4; ++j)
for(index k = 0; k != 2; ++k)
assert(A[i][j][k] == verify++);
return 0;
}
代码中的重要部分是我们从用户处获取维度并使用以下内容创建数组的主要功能:
const unsigned int DIMENSION_COUNT = 3; // dimension count for this test application, change it at will :)
// here is the type of the multi-dimensional (DIMENSION_COUNT dimensions here) array we want to use
// for this example, it own texts
typedef boost::multi_array< std::string , DIMENSION_COUNT > TextMatrix;
// this provide size/index based position for a TextMatrix entry.
typedef std::tr1::array<TextMatrix::index, DIMENSION_COUNT> Position; // note that it can be a boost::array or a simple array
/* This function will allow the user to manipulate the created array
by managing it's commands.
Returns true if the exit command have been called.
*/
bool process_command( const std::string& entry, TextMatrix& text_matrix );
/* Print the position values in the standard output. */
void display_position( const Position& position );
int main()
{
std::cout << "Multi-Array test!" << std::endl;
// get the dimension informations from the user
Position dimensions; // this array will hold the size of each dimension
for( int dimension_idx = 0; dimension_idx < DIMENSION_COUNT; ++dimension_idx )
{
std::cout << "Please enter the size of the dimension "<< dimension_idx <<" : ";
// note that here we should check the type of the entry, but it's a simple example so lets assume we take good numbers
std::cin >> dimensions[dimension_idx];
std::cout << std::endl;
}
// now create the multi-dimensional array with the previously collected informations
TextMatrix text_matrix( dimensions );
std::cout << "Text matrix with " << DIMENSION_COUNT << " dimensions of size ";
display_position( dimensions );
std::cout << " have been created."<< std::endl;
std::cout << std::endl;
std::cout << "Ready!" << std::endl;
std::cout << "Type 'help' for the command list." << std::endl;
std::cin.sync();
// we can now play with it as long as we want
bool wants_to_exit = false;
while( !wants_to_exit )
{
std::cout << std::endl << ">" ;
std::tr1::array< char, 256 > entry_buffer;
std::cin.getline(entry_buffer.data(), entry_buffer.size());
const std::string entry( entry_buffer.data() );
wants_to_exit = process_command( entry, text_matrix );
}
return 0;
}
const unsigned int DIMENSION_COUNT=3;//此测试应用程序的维度计数,请随意更改:)
//这是我们想要使用的多维数组(这里是DIMENSION\u COUNT dimensions)的类型
//在这个例子中,它拥有自己的文本
typedef boost::multi_数组TextMatrix;
//这将为TextMatrix条目提供基于大小/索引的位置。
typedef std::tr1::array Position;//请注意,它可以是boost::array或简单数组
/*此函数将允许用户操作创建的数组
通过管理它的命令。
如果已调用exit命令,则返回true。
*/
bool process_命令(const std::string&entry、TextMatrix&text_matrix);
/*打印标准输出中的位置值*/
无效显示位置(常数位置和位置);
int main()
{
Std::CUT< P>如果你使用C而不是C++,你可能想看看Dave Hanson库中的ARRAYT抽象。它非常干净,设计得很好。我让学生做二维版本作为练习。你可以这样做,或者只写一个附加函数,做索引映射,例如。
void *Array_get_2d(Array_T a, int width, int height, int i, int j) {
return Array_get(a, j * width, i, j);
}
使用一个单独的结构来存储宽度、高度和指向元素的指针会更简洁一些。不使用boost的标准方法是使用std::vector:
std::vector< std::vector<int> > v;
v.resize(rows, std::vector<int>(cols, 42)); // init value is 42
v[row][col] = ...;
但这将失去使用[x][y]
对向量进行索引的功能。您还必须将行数和列数存储在某个位置,而使用嵌套解决方案时,您可以使用v.size()
获得行数,使用v[0].size()获得列数
使用boost,您可以使用boost::multi_array
,这正是您想要的(请参阅另一个答案)
还有使用原生C++数组的原始方法。这是非常有用的,而且绝对不比嵌套向量解决方案好:
int ** rows = new int*[row_count];
for(std::size_t i = 0; i < row_count; i++) {
rows[i] = new int[cols_count];
std::fill(rows[i], rows[i] + cols_count, 42);
}
// use it... rows[row][col] then free it...
for(std::size_t i = 0; i < row_count; i++) {
delete[] rows[i];
}
delete[] rows;
int**rows=newint*[row_count];
对于(std::size\u t i=0;i|
你必须存储你在某处创建的列和行的数量,因为你不能从指针接收到它们。
< P > 2D C样式数组在C和C++中是一个大小为“代码>行*列* siZeof(数据类型)< /COD>字节的内存块。< /P>
实际的[row][column]维度在编译时只静态存在,在运行时没有动态存在
因此,正如其他人所提到的,您可以实现
int array [ rows ] [ columns ];
作为:
或作为:
int * array = malloc ( rows * columns * sizeof(int) );
下一步:声明大小可变的数组。在C中这是可能的:
int main( int argc, char ** argv )
{
assert( argc > 2 );
int rows = atoi( argv[1] );
int columns = atoi( argv[2] );
assert(rows > 0 && columns > 0);
int data [ rows ] [ columns ]; // Yes, legal!
memset( &data, 0, sizeof(data) );
print( rows, columns, data );
manipulate( rows, columns, data );
print( rows, columns, data );
}
在C中,只需将可变大小的数组与非可变大小的数组传递相同的值:
void manipulate( int theRows, int theColumns, int theData[theRows][theColumns] )
{
for ( int r = 0; r < theRows; r ++ )
for ( int c = 0; c < theColumns; c ++ )
theData[r][c] = r*10 + c;
}
或者最好(使用自动内存管理)
std::向量数组(行*cols);
然后必须修改函数以接受一维数据:
void manipulate( int theRows, int theColumns, int *theData )
{
for ( int r = 0; r < theRows; r ++ )
for ( int c = 0; c < theColumns; c ++ )
theData[r * theColumns + c] = r*10 + c;
}
void操纵(int theRows、int theColumns、int*theData)
{
for(int r=0;r 在C++中有两种表示二维数组的方法,一种比另一种更灵活。
数组的数组
首先创建一个指针数组,然后用另一个数组初始化每个指针
// First dimension
int** array = new int*[3];
for( int i = 0; i < 3; ++i )
{
// Second dimension
array[i] = new int[4];
}
// You can then access your array data with
for( int i = 0; i < 3; ++i )
{
for( int j = 0; j < 4; ++j )
{
std::cout << array[i][j];
}
}
//第一维度
整数**数组=新整数*[3];
对于(int i=0;i<3;++i)
{
//第二维度
数组[i]=新整数[4];
}
//然后,您可以使用访问阵列数据
对于(int i=0;i<3;++i)
{
对于(int j=0;j<4;++j)
{
std::cout您可以使用malloc来实现这一点,并且仍然可以通过普通数组[][]来访问它,而不是使用数组[rows*cols+cols]方法
main()
{
int i;
int rows;
int cols;
int **array = NULL;
array = malloc(sizeof(int*) * rows);
if (array == NULL)
return 0; // check for malloc fail
for (i = 0; i < rows; i++)
{
array[i] = malloc(sizeof(int) * cols)
if (array[i] == NULL)
return 0; // check for malloc fail
}
// and now you have a dynamically sized array
}
main()
{
int i;
int行;
int cols;
int**array=NULL;
数组=malloc(sizeof(int*)*行);
if(数组==NULL)
返回0;//检查malloc失败
对于(i=0;i
我最近遇到了一个类似的问题。我没有可用的Boost。与普通数组相比,向量向量的速度非常慢。拥有一个指针数组会使初始化变得更加困难,因为你必须迭代每个维度并初始化指针,可能会有一些非常复杂的问题使用过程中的级联类型,可能有很多typedef
免责声明:我不确定我是否应该将此作为
void manipulate( int theRows, int theColumns, int theData[theRows][theColumns] )
{
for ( int r = 0; r < theRows; r ++ )
for ( int c = 0; c < theColumns; c ++ )
theData[r][c] = r*10 + c;
}
int *array = new int[rows * cols]();
std::vector<int> array(rows * cols);
void manipulate( int theRows, int theColumns, int *theData )
{
for ( int r = 0; r < theRows; r ++ )
for ( int c = 0; c < theColumns; c ++ )
theData[r * theColumns + c] = r*10 + c;
}
// First dimension
int** array = new int*[3];
for( int i = 0; i < 3; ++i )
{
// Second dimension
array[i] = new int[4];
}
// You can then access your array data with
for( int i = 0; i < 3; ++i )
{
for( int j = 0; j < 4; ++j )
{
std::cout << array[i][j];
}
}
int* buffer = new int[3*4];
int** array = new int*[3];
for( int i = 0; i < 3; ++i )
{
array[i] = array + i * 4;
}
// You can then access your array data with
for( int i = 0; i < 3; ++i )
{
for( int j = 0; j < 4; ++j )
{
const int index = i * 4 + j;
std::cout << buffer[index];
}
}
main()
{
int i;
int rows;
int cols;
int **array = NULL;
array = malloc(sizeof(int*) * rows);
if (array == NULL)
return 0; // check for malloc fail
for (i = 0; i < rows; i++)
{
array[i] = malloc(sizeof(int) * cols)
if (array[i] == NULL)
return 0; // check for malloc fail
}
// and now you have a dynamically sized array
}
template <typename T>
class Array2D {
private:
std::unique_ptr<T> managed_array_;
T* array_;
size_t x_, y_;
public:
Array2D(size_t x, size_t y) {
managed_array_.reset(new T[x * y]);
array_ = managed_array_.get();
y_ = y;
}
T* operator[](size_t x) const {
return &array_[x * y_];
}
};
auto a = Array2D<int>(x, y);
a[xi][yi] = 42;
void manipulate(int rows, int cols, int (*data)[cols]) {
for(int i=0; i < rows; i++) {
for(int j=0; j < cols; j++) {
printf("%d ", data[i][j]);
}
printf("\n");
}
}
int main() {
int rows = ...;
int cols = ...;
int (*data)[cols] = malloc(rows*sizeof(*data));
manipulate(rows, cols, data);
free(data);
}