我的学校还有另一项任务是:
Write a program which will output the largest from three inputed numbers
到目前为止,我已经这样做了:
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
int* numbers = new int[3];
for(int i = 0; i < 3; i++) {
cout << "Input number no. " << (i + 1);
cin >> numbers[i];
cout << endl;
}
system("PAUSE");
return EXIT_SUCCESS;
}
C++ 中是否有辅助函数/方法可以在我的 numbers
数组中找到最大的数字?
最佳答案
有一种算法可以在容器 ( std::max_element
) 中找到最大元素,但这是不合适的。您的情况可以通过恒定 内存消耗来解决,因此您不需要存储所有数字。在任何给定点,您只需要记住当前的最大值。
想象一下,您必须处理无数个数字。然后将它们全部存储起来是不可取的。
当然,max_element
算法在内部与我刚才建议的一样,但它假设您已经拥有容器。如果你不这样做,那么只需即时更新最大值。 boost.accumulators 库可以执行此操作,但我相信您可以自己编写它 — 它应该只需要一两行。
关于c++ - 从 C++ 中的整数数组中获取最大数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13224543/