数组 2D 多个值

Array 2D multiple values

本文关键字:2D 数组      更新时间:2023-10-16

我有一个 2d 数组,该行获取名称,列获取年龄但我对此有点错过。

我将留下一个伪代码。

#include <iostream>
int main()
{
    std::cout << "Hello World!n";
    int a[4][1];
    int i, j;
    for (i = 0; i < 4; i++)
    {
        for (j = 0; j < 1; j++)
        {
            a[i][j] = name, age;
        }
    }
}

应该返回类似以下内容:

a[0][0] = "joao",12
a[1][1] = "maria",22
a[2][2] = "jose",40
a[3][3] = "jose",50

首先,你的类型是错误的。 a 有整数,而名称不完全是整数。

更好的解决方案(使用 STL)是使用一对字符串和一个整数(您可以使用字符来处理所有重要的事情,除非您希望人们有 2,147,483,000 岁)。

int array_size = 4; // as an example
// the array, but now the type is of a pairing of string and integer.
std::array<std::pair<std::string, int>, array_size> a; 
a[0] = {"joao", 12}; // how to set a name 

或者你想要的任何名字。