二维数组值 C++

2D array values C++(二维数组值 C++)

本文介绍了二维数组值 C++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想声明一个二维数组并为其赋值,而不需要运行 for 循环.

我认为我可以使用以下想法

int array[5] = {1,2,3,4,5};

这也可以很好地初始化二维数组.但显然我的编译器不喜欢这个.

/*1 8 12 20 255 9 13 24 26*/#include int main(){int arr[2][5] = {0};//这实际上将所有内容初始化为 0.arr [1] [] = {1,8,12,20,25};//第 11 行arr [2] [] = {5,9,13,24,26};返回0;}

<块引用>

J:CPPGrid>bcc32.exe Grid.cpp

Borland C++ 5.5.1 for Win32 版权所有 (c) 1993, 2000 Borland

Grid.cpp:

Error E2188 Grid.cpp 11:函数 main() 中的表达式语法

Error E2188 Grid.cpp 12:函数 main() 中的表达式语法

警告 W8004 Grid.cpp 14:'arr' 被分配了一个从未在函数中使用的值离子主()

* 2 编译错误 *

请帮助了解使用我的一组值初始化二维数组的正确方法是什么.

解决方案

像这样:

int main(){int arr[2][5] ={{1,8,12,20,25},{5,9,13,24,26}};}

这应该在你的 C++ 教科书中涵盖:你在使用哪一本?

无论如何,最好考虑使用 std::vector 或一些现成的矩阵类,例如来自 Boost.

I wanted to declare a 2D array and assign values to it, without running a for loop.

I thought I could used the following idea

int array[5] = {1,2,3,4,5};

Which works fine to initialize the 2D array as well. But apparently my compiler doesn't like this.

/*
 1   8  12  20  25
 5   9  13  24  26
*/

#include <iostream.h>

int main()
{
    int arr[2][5] = {0};   // This actually initializes everything to 0.
    arr [1] [] = {1,8,12,20,25}; // Line 11
    arr [2] [] = {5,9,13,24,26};
    return 0;
}

J:CPPGrid>bcc32.exe Grid.cpp

Borland C++ 5.5.1 for Win32 Copyright (c) 1993, 2000 Borland

Grid.cpp:

Error E2188 Grid.cpp 11: Expression syntax in function main()

Error E2188 Grid.cpp 12: Expression syntax in function main()

Warning W8004 Grid.cpp 14: 'arr' is assigned a value that is never used in funct ion main()

* 2 errors in Compile *

Please help as to what is the right way to initialize the 2d array with my set of values.

解决方案

Like this:

int main()
{
    int arr[2][5] =
    {
        {1,8,12,20,25},
        {5,9,13,24,26}
    };
}

This should be covered by your C++ textbook: which one are you using?

Anyway, better, consider using std::vector or some ready-made matrix class e.g. from Boost.

这篇关于二维数组值 C++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:二维数组值 C++

基础教程推荐