gpt4 book ai didi

c++ - Vector C++ 的索引/最大值/最小值

转载 作者:行者123 更新时间:2023-11-30 01:19:08 26 4
gpt4 key购买 nike

我希望能够找出 vector 中最高和最低的元素,并找出高/低数字当前的位置/索引。例如,

vector<double> x;
std::cout << "Enter in #s: ";
double numbers;
std::getline(std::cin, numbers);
x.push_back(numbers);

假设用户输入 4.3 1.0 2.99 43.5

我想要的结果是

The highest number is 43.5 at position 4
The lowest number is 1.0 at position 2

我想知道是否有任何方法可以在不使用 min_element/max_element 函数的情况下使用 for 循环来实现此代码?

我想使用类似的东西:

for (int i=0;i < x.size();i++)
if ( //the number is less than ) {
std::cout << "The lowest number is...... at position .....";
if ( //the number is greather than ) {
std::cout << "The highest number is......at position......";

最佳答案

将每个数字与迄今为止找到的最佳最大值/最小值进行比较。
如果它更大/更小,用它替换最大/最小值并记下索引

您将需要一个最大和最小变量以及两个索引 - 如果您的最大和最小值设置为初始值,请注意您设置的初始值

关于c++ - Vector<double> C++ 的索引/最大值/最小值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21324170/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com