【问题标题】:How to search within an array thats within struct?如何在结构内的数组中搜索?
【发布时间】:2016-05-30 06:55:10
【问题描述】:

我无法理解内存分配。

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

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

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

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

【问题讨论】:

  • 过去[12]??过去[9] 已定义。此外,AccountInfo->number 无效。您将不得不为此创建一个结构指针。否则,您可以将结构变量设为 acc 并使用 acc.number。同样, acc.past[i] 为您提供过去数组的第 i 个元素。
  • 怎么过去[12]?不是最大尺寸索引 8 吗? pass[9] 的最大索引是过去[8]。
  • AccountInfo info; /* set up its values */; int* min = std::min_element(std::begin(info.past), std::end(info.past));(同样使用std::max_element())。
  • 糟糕,这是一个错字。对此感到抱歉。

标签: c++ arrays struct


【解决方案1】:

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

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

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
}

【讨论】:

  • 在这种情况下可以将i&lt;sizeof(st_AccInfo.past) 替换为i&lt;9,因为数组的大小已经初始化?
  • @digggzz 是的,你可以。
【解决方案2】:

好吧,当您将past 声明为一个由 9 个整数组成的数组时,就像 C++ 从 0 开始计数索引一样,您可以在不调用未定义行为的情况下使用更大的索引是 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

【讨论】:

    猜你喜欢
    • 2017-07-30
    • 2013-04-30
    • 1970-01-01
    • 1970-01-01
    • 2020-03-25
    • 2014-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多