存储函数的迭代结果,并在被另一个函数调用时使用它们

时间:2016-04-11 23:51:41

标签: c++ loops

我有三个功能,例如:

void firstFunc(entry) {
     this function returns list of entries that are stored in an array
}

void secondFunc() {
    while (loop x number of times) {
        firstFunc(the value here gets updated with the next entry every loop);
        compare the updated entry with another local parameter that is set within this method;
        if lesser { do something; }
    }     
}

void thirdFunc() {
    while (loop x number of times) {
        firstFunc(the value here gets updated with the next entry every loop);
        compare the updated entry with another local parameter that is set within this method;
        if greater { do something; }
    }     
}

这里,“firstFunc”循环两次(一次在“secondFunc”中,然后在“thirdFunc”中)。我想要的就是这样:

void firstFunc(entry) {
     this function returns list of entries that are stored in an array
}

while (loop x number of times) {
        firstFunc(the value here gets updated with the next entry every loop);
}

void secondFunc() {
    while (loop x number of times) {
        use the value next updated value from firstFunc;
        compare the updated entry with another local parameter that is set within this method;
        if lesser { do something; }
    }     
}

void thirdFunc() {
    while (loop x number of times) {
        use the value next updated value from firstFunc;
        compare the updated entry with another local parameter that is set within this method;
        if greater { do something; }
    }     
}

在上面的代码中,firstFunc的循环执行一次,而不是在secondFunc和thirdFunc中执行。我的问题是如何实现这一目标?

1 个答案:

答案 0 :(得分:0)

您可以使用数组来记忆每个firstFunc()的结果。

memoArr = []
while (loop x number of times) {
    memoArr[x] = firstFunc(the value here gets updated with the next entry every loop);
}

第二个和第三个函数使用数组中的值,而不是再次调用函数。