我希望能够将struct成员传递给函数:
struct threeBuckets {
int bucketA;
int bucketB;
int bucketC;
};
threeBuckets allCombinations[512000] = {{0,0,0}};
int totalCombinations = 1;
int counter = 0;
//note that pourer, receiver, and other are one of the struct members (bucketA, bucketB, and bucketC)
void pour(pourer, receiver, int receiverCap, other) {
int finalTriple[3];
allCombinations[totalCombinations].bucketA = allCombinations[counter].bucketA;
allCombinations[totalCombinations].bucketB = allCombinations[counter].bucketB;
allCombinations[totalCombinations].bucketC = allCombinations[counter].bucketC;
allCombinations[totalCombinations].receiver = allCombinations[totalCombinations].receiver + allCombinations[counter].pourer;
allCombinations[totalCombinations].pourer = 0;
if (allCombinations[totalCombinations].receiver > receiverCap) {
allCombinations[totalCombinations].pourer = allCombinations[totalCombinations].pourer + allCombinations[totalCombinations].receiver - receiverCap;
allCombinations[totalCombinations].receiver = receiverCap;
}
finalTriple[0] = allCombinations[totalCombinations].bucketA;
finalTriple[1] = allCombinations[totalCombinations].bucketB;
finalTriple[2] = allCombinations[totalCombinations].bucketC;
//some more irrelevant code
}
正如我已经明确指出的那样,参数pourer,receiver和其他参数分别是bucketA,bucketB和bucketC(没有特定的顺序,该顺序的确取决于我调用该函数的时间。)在几个地方我要修改实例
allCombinations[totalCombinations].pourer
例如。如何将struct成员用作参数,以及使用哪种类型来指定它?
注意:我主要是初学者,并且是StackOverflow的新手,因此,如果我做的其他任何事情是错误的,请随时告诉我。
注2:如果您中有一个曾经或曾经做过USACO,您可能会将此问题识别为milk3培训网关问题。如果您不知道我在这里做什么,这可能会对您有所帮助。
答案 0 :(得分:3)
听起来pour
中的参数类型需要使用指向成员变量的指针。
void pour(double threeBuckets::(*pourer) ,
double threeBuckets::(*receiver),
int receiverCap,
double threeBuckets::(*other)) {
...
}
在函数中,更改用法
allCombinations[totalCombinations].pourer
allCombinations[totalCombinations].receiver
allCombinations[totalCombinations].other
通过
allCombinations[totalCombinations].*pourer
allCombinations[totalCombinations].*receiver
allCombinations[totalCombinations].*other
分别。
在调用函数时,使用:
pour(&threeBuckets::bucketA,
&threeBuckets::bucketB,
0, // Any appropriate value
&threeBuckets::bucketC);
另一个值得考虑的选择是:
threeBuckets
以使用数组。pour
作为数组的索引。
struct threeBuckets {
int buckets[3];
};
void pour(int pourerIndex ,
int receiverIndex,
int receiverCap,
int otherIndex)) {
...
}
然后,而不是使用
allCombinations[totalCombinations].pourer
allCombinations[totalCombinations].receiver
allCombinations[totalCombinations].other
使用
allCombinations[totalCombinations].buckets[pourerIndex]
allCombinations[totalCombinations].buckets[receiverIndex]
allCombinations[totalCombinations].buckets[otherIndex]
当然,将调用更改为使用索引。
pour(0,
1
0, // Any appropriate value
2);