C++ 如何在struct中的数组中搜索?
我无法理解内存分配 例如,如果我有一个结构,如下所示:C++ 如何在struct中的数组中搜索?,c++,arrays,struct,C++,Arrays,Struct,我无法理解内存分配 例如,如果我有一个结构,如下所示: struct AccountInfo{ int number; int balance; int past[9]; int minimum_past; int maximum_past; }; 如何通过[9]访问阵列?一个更直接的问题是,我如何找到过去的最小值和最大值,然后将这些值分配给过去的最小值和最大值 我知道要将结构中的成员设置为某些值,我可以做一些类似于AccountInfo->n
struct AccountInfo{
int number;
int balance;
int past[9];
int minimum_past;
int maximum_past;
};
如何通过[9]访问阵列?一个更直接的问题是,我如何找到过去的最小值和最大值,然后将这些值分配给过去的最小值和最大值
我知道要将结构中的成员设置为某些值,我可以做一些类似于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
}
int x=st_AccInfo.number;
对于(inti=0;i我给你举了一个简单的例子
在头文件中定义结构:
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
}
int x=st_AccInfo.number;
对于(int i=0;i),当您声明“代码>过去<代码> >作为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
AccountInfo;//创建一个结构
AccountInfo*paccountInfo=&AccountInfo;//定义指向它的指针
accountInfo.last[8]=12;//直接访问
CUT最后[ 8 ] < P>,正如您声明的代码>过去< /C> >作为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
AccountInfo;//创建一个结构
AccountInfo*paccountInfo=&AccountInfo;//定义指向它的指针
accountInfo.last[8]=12;//直接访问
cout last[8]pass[12]?定义了pass[9]。此外,AcccountInfo->number无效。您必须为此创建一个结构指针。否则,您可以使结构变量显示为acc并使用acc.number。类似地,acc.pass[i]给出了pass数组的第i个元素。为什么pass[12]?它不是最大大小索引8吗?pass[9]的最大索引超过了[8].AccountInfo;/*设置它的值*/;int*min=std::min_元素(std::begin(info.pass),std::end(info.pass));
(同样使用std::max_元素()
)。哎呀,这是个打字错误。很抱歉。过去[12]?过去[9]已定义。此外,AcccountInfo->number无效。您必须为此创建一个结构指针。否则,您可以将结构变量设置为acc并使用acc.number。类似地,acc.pass[i]将为您提供过去数组的第i个元素。为什么过去[12]?它不是最大大小索引8吗?pass[9]的最大索引超过了[8].AccountInfo;/*设置其值*/;int*min=std::min_元素(std::begin(info.pass),std::end(info.pass));
(同样使用std::max_元素()
)。哎呀,这是一个打字错误。很抱歉。cani@digggzz是的,你可以。可以i@digggzz是的,你可以。