(Qt/C++)int数组中的多个值

(Qt/C++) Multiple Values in int Array

本文关键字:数组 int Qt C++      更新时间:2023-10-16

我正在处理一个项目,如果我能用多个int值填充一个int数组,那会容易得多。

例如:

int array[5];
array[0] == 10, 20, 30;
array[1] == 44, 55, 66;
...

这对我来说有点难以解释,但我如何用多个int值填充数组?感谢您抽出时间:)

您可以声明一个多维数组:

int array[5][3];
array[0][0] = 10; array[0][1] = 20; array[0][2] = 30;
array[1][0] = 44; array[1][1] = 55; array[2][2] = 66;
...

或者创建一个自组织结构的数组:

struct tuple_3int
{
    int x, y, z;
    tuple_3int() {} 
    tuple_3int(int X, int Y, int Z) : x(X), y(Y), z(Z) {}
};
tuple_3int array[5];
array[0] = tuple_3int(10, 20, 30);
array[1] = tuple_3int(44, 55, 66);

或者,如果您使用C++11,您可以使用新的元组,并声明一个3 int的元组数组:

#include <tuple>
std::tuple<int, int, int> array[5];
array[0]=std::make_tuple(10, 20, 30);
array[1]=std::make_tuple(44, 55, 66);

为什么不使用2D数组?!如果每个单元格中要保存的元素数量不相等,则可以使用向量数组或列表数组

例如

vector<int> array[5];

您可以通过不同的方式实现目标:

  1. 创建一个int的三重类,并创建该类的数组

class triple {
int x;
int y;
int z;
public:
triple (int _x, int _y, int _z) : x(_x), y(_y), z(_z) {}
};

三重数组[SIZE];array[0]=三重(1,2,3);

  1. 输入int normal的值,并将每3个连续单元格引用为1个索引

array[0] = 10;    
array[1] = 44;   
array[2] = 20;   
array[3] = 55;   
array[4] = 30;   
array[5] = 66;  

超过0-2个索引将是你的第一个单元格,3-5个是第二个单元格,依此类推

  1. 创建二维阵列

int array [SIZE][3];
array [i][0] = 1;
array [i][1] = 2;
array [i][2] = 3;

假设您可以使用C++11,那么std::tuplestd::vector似乎是一种简单的方法,这里有一个简单的例子:

#include <iostream>
#include <vector>
#include <tuple>
int main()
{
    std::vector<std::tuple<int,int,int>> tupleVector ;
    tupleVector.push_back( std::make_tuple( 10, 20, 30 ) ) ;
    tupleVector.push_back( std::make_tuple( 44, 55, 66 ) ) ;
    std::cout << std::get<0>( tupleVector[0] ) << ":" << std::get<1>( tupleVector[0] )  << ":" << std::get<2>( tupleVector[0] )  << std::endl ;
    std::cout << std::get<0>( tupleVector[1] ) << ":" << std::get<1>( tupleVector[1] )  << ":" << std::get<2>( tupleVector[1] )  << std::endl ;
}

一个非C++11的例子可以使用struct来保存插槽数据,你可以坚持使用数组,但std::vector更简单,从长远来看不会让你头疼:

#include <iostream>
#include <vector>
#include <tuple>
struct slot
{
    int x1, x2, x3 ;
    slot() : x1(0), x2(0), x3() {}   // Note, need default ctor for array example
    slot( int p1, int p2, int p3 ) : x1(p1), x2(p2), x3(p3) {}  
} ;
int main()
{
    std::vector<slot> slotVector ;
    slotVector.push_back( slot( 10, 20, 30 ) ) ;
    slotVector.push_back( slot( 44, 55, 66 ) ) ;
    std::cout << slotVector[0].x1 << ":" << slotVector[0].x2 << ":" << slotVector[0].x3 << std::endl ;
    slot slotArray[5] ;
    slotArray[0] = slot( 10, 20, 30 ) ;
    slotArray[0] = slot( 44, 55, 66 ) ;
    std::cout << slotArray[0].x1 << ":" << slotArray[0].x2 << ":" << slotArray[0].x3 << std::endl ;
}