[英]C++ Arrays do the same as structs
#include <iostream>
using namespace std;
const int MAXACCOUNTS =8;
int count1 = 1;
bool True = true;
int main()
{
int AccountNumber[MAXACCOUNTS] = {1001, 7940, 4382, 2651, 3020, 7168, 6245, 9342};
double Balance[MAXACCOUNTS] = {4254.40, 27006.25, 123.50, 85326.92, 657.0, 7423.34, 4.99, 107864.44};
int DaysSinceDebited[MAXACCOUNTS] = {20, 35, 2, 14, 5, 360, 1, 45};
while (count1 != MAXACCOUNTS)
{
if (Balance[count1] > 10000 && DaysSinceDebited[count1] > 30)
{
cout << AccountNumber[count1] << " ";
cout << Balance[count1] << " ";
cout << Balance[count1] / 100 * 3 << endl;
}
else if (True = true)
{
cout << AccountNumber[count1] << " ";
cout << Balance[count1] << " ";
cout << Balance[count1] / 100 * 3 << endl;
}
count1 ++;
}
return 0;
}
嗨,大家好
我刚开始使用 C++,但被卡住了。 我正在为考试而练习,其中一项要求是使用结构使该程序执行相同的操作。 我确定它很简单,有人可以帮忙解释一下吗?
既然是作业,我不会给你答案,而是会试着帮助你理解如何自己完成作业。
您正在使用三个相同大小的数组。
正如您现在可能知道的那样,您可以创建一个结构来存储多个数据
这个问题似乎没有说明你不能使用数组,所以我猜你可以使用一个包含一些数据的数组;)
我希望这些线索可以帮助您走上正轨。
在 C++ 中,数组和结构是聚合类型。 您可能会将它们视为可以放置“东西”的“盒子”。 在数组“盒子”中,您可以放置相同类型的东西并通过它们的索引来引用这些东西。 在 struct "box" 中,您可以放置多种可能是不同种类的东西,并且您可以给它们命名以便以后引用它们。
诀窍是您可以将一个“盒子”嵌套在另一个“盒子”中:例如,您可以将数组“盒子”放入结构“盒子”中,将结构“盒子”放入数组“盒子”中。 这个练习很可能是关于嵌套的顺序。
这是一个小插图(伪 C++):
// Struct of Arrays (SoA)
// Put things into arrays, then put arrays into a struct
// (Like in your code, but arrays are wrapped into a struct)
struct Entries {
int AccountNumber[MAXACCOUNTS];
double Balance[MAXACCOUNTS];
int DaysSinceDebited[MAXACCOUNTS];
};
Entries entries;
// Read a "thing" from SoA
ith_account_number = entries.AccountNumber[i];
// Write a "thing" into SoA
entries.AccountNumber[i] = ith_account_number;
// Array of Structs (AoS)
// Put things into a struct, then put structs into an array
struct Entry {
int AccountNumber;
double Balance;
int DaysSinceDebited;
};
Entry entries[MAXACCOUNTS];
// Read a "thing" from AoS:
ith_account_number = entries[i].AccountNumber;
// Write a "thing" into AoS:
entries[i].AccountNumber = ith_account_number;
数据聚合模式的选择对数据的内存布局、性能特征和代码风格有着深远的影响。 有人可能会说,AoS 看起来更像是“面向对象”的方法(想想 Java 类),而 SoA 更像是“基于数组”的编程(想想 FORTRAN 或 NumPy)。
希望有这个小帮手可以轻松解决你的运动问题。 实际上,唯一不同的是您访问条目的方式(用于读取和写入)。
使用 AccountNumber、Balance 和 DaysSinceDebited 创建一个struct
作为它的成员变量。
你的stuct
应该是这样的:
struct Account {
int AccountNumber;
double Balance;
int DaysSinceDebited;
}
然后创建一个包含所需元素数量的 Account 数组,然后通过传递必要的数据来初始化每个元素。
例如:
AccountDatabase Account[6];
AccountDatabase[1].AccountNumber = 1001;
AccountDatabase[1].Balance= 4254.40;
AccountDatabase[1].DaysSinceDebited = 20;
对于每个元素,依此类推。
对于从结构中提取数据的地方,请使用以下语法:
例如读取AccountDatabase第一个元素中存储的Account number,
AccountDatabase[1].AccountNumber
因此,您的cout << AccountNumber[count1] << " ";
变得像
cout << AccountDatabase[count1].AccountNumber << " ";
对于你的余额来说,它是
cout << AccountDatabase[count1].Balance<< " ";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.