c ++数组,如何在同一数组中添加新的值行? [英] c++ arrays, how to add a new row of values in the same array?

查看:103
本文介绍了c ++数组,如何在同一数组中添加新的值行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何通过用户输入或cin在数组中创建新的值行?

how do you create a new row of values in an array from user input or cin?

假设数组中已经存在一行值,您需要添加第二行值
但不将其添加到第一行,您如何将大括号和逗号放入,用户是否将其放入,或者是否存在将自动将括号和逗号放入

say theres a row of values already in the array and you need to add a second row of values but not added to the first row, and how would you put the braces and the comma in, does the user put it in or is there something that will automatically put the bracers and comma in

int test [] = { 1, 21, 771, 410, 120711 },
{ 1, 2, 3, 4, 5 };


推荐答案

您要的是二维数组。声明如下:

You're asking for a two-dimensional array. This is declared like this:

int test[][5] = {
    {1, 21, 771, 410, 120711},
    {1, 2, 3, 4, 5 },
    // Add more if you want.
};

第一个数组通过 test [0] ,第二个通过 test [1] ,依此类推。第一个数组的第一个元素是 test [0] [0] ,第二个 test [0] [1] 等。

The first array is accessed through test[0], the second through test[1], etc. The first element of the first array is test[0][0], the second test[0][1] and so forth.

请注意,这是具有静态大小的数组。您无法在运行时更改它。如果您事先知道需要多少行,只需将其声明为:

Note that this is an array with a static size. You can't change it at runtime. If you know in advance how many rows you need, you just declare it as:

int test[NUMBER OF ROWS][NUMBER OF COLUMNS];

,然后在后面填充值。但是您不能更改大小。如果要使用完全动态的数组,则应使用向量的向量:

and then fill it with values later. But you cannot change the size. If you want a fully dynamic array, then you should use a vector of vectors:

std::vector< std::vector<int> > test;

然后添加以下行:

test.push_back(std::vector<int>());

并使用以下命令将元素添加到每一行:

and add elements to each row with:

// Adds a number to the first row.
test[0].push_back(some_int);

访问与静态数组( test [0] test [0] [0] 等)

Access happens the same way as with the static array (test[0], test[0][0], etc.)

这篇关于c ++数组,如何在同一数组中添加新的值行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆