如何在结构中的数组中搜索

How to search within an array thats within struct?

本文关键字:搜索 数组 结构      更新时间:2023-10-16

我在理解内存分配方面遇到了麻烦。

例如,如果我有一个结构,如下所示:

struct AccountInfo{
     int number;
     int balance;
     int past[9];
     int minimum_past;
     int maximum_past;
};

我将如何访问阵列past[9]?一个更直接的问题是我如何找到past的最小值和最大值,然后将这些值分配给minimum_pastmaximum_past

我知道要将结构中的成员设置为某些值,我可以做类似AccountInfo -> number = 10;的事情,但是对于数组,我仍然感到困惑。

我给你做了一个简单的例子。

在头文件中定义你的结构:

struct AccountInfo{
     int number;
     int balance;
     int past[9];
     int minimum_past;
     int maximum_past;
};

在您的 CPP 文件中:

AccountInfo st_AccInfo;

访问您的结构:

int x = st_AccInfo.number;
for(int i=0; i<sizeof(st_AccInfo.past); i++)
{
   // Navigate your Array from index 0 to 8
}

好吧,当您将past声明为 9 个整数的数组时,就像从 0 开始计数索引一样C++,您可以在不调用未定义行为的情况下使用的更大索引是 8。

话虽如此,您使用的数组元素与其他结构元素完全相同:

AccountInfo accountInfo;   // create a struct
AccountInfo* paccountInfo = &accountInfo;  // define a pointer to it
accountInfo.last[8] = 12;  // direct access
cout << paccountInfo->last[8] << endl;    // access through pointer - outputs 12