c++ - 我的 If Else 语句无法提供 vector 中的最大值 (C++)

标签 c++ loops for-loop if-statement

我正在尝试返回最大值。 C++ 中 vector 中的值,但我经常只得到最后一个值作为响应(我猜这是因为 if-else 循环不知何故没有进行比较,只是将下一个值分配给“maxVal”)。例如,下面的代码返回 30 作为答案。我究竟做错了什么?你能帮忙吗?

下面是代码->

#include <iostream>
#include <cstdlib>
#include <cmath>
#include <string>
#include <fstream>
#include <vector>

using namespace std;

double max (const vector<double>& myVector)   {
int n = myVector.size();
double maxVal;
for (int i=0; i<=n-1; i++) {
    if (maxVal <= myVector[i+1])  {
        maxVal = myVector[i+1];   
    }
    else {
        maxVal = myVector[i];
    }

}
return maxVal; 
}

int main() {
vector<double> testVector;
testVector.push_back(10.0);
testVector.push_back(200.0);
testVector.push_back(30.0);
cout << max(testVector);
return 0;

}

最佳答案

C++ 有一个丰富的库,我不明白为什么人们不使用它。 这是一个两行版本,用于查找 vector 的最大值。请不要重新发明轮子。

#include <iostream>                                                                                                                                                                                                
#include <vector>                                                                                                                                                                                                  
#include <algorithm>                                                                                                                                                                                                

int main()                                                                                                                                                                                                         
{                                                                                                                                                                                                                  
  auto v = std::vector{4, 3, 2, 1};                                                                                                                                                                               
  std::cout << *max_element(v.cbegin(), v.cend()) << "\n";                                                                                                                                                         
}                                                                                                                                                                                                                  

关于c++ - 我的 If Else 语句无法提供 vector 中的最大值 (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52762824/

相关文章:

python - 在 for 循环中调用对象

c++ - 垒球 C++ 问题 : How to compare two arrays for equality?

c++ - 在仍有引用时调用析构函数

c - 为什么迭代数字中的每个数字并发现均分数字不起作用?

c - 输入用户的密码并检查它是否包含字符、字母和数字

loops - Lua for 循环不进行所有迭代

c# - 如何创建一个非重复随机数数组

c++ - 防止随机整数不断被重新分配

c++ - C++ 中的 exit 和 std::exit 有什么区别?

c - 如何循环一个整数数组并将正数和负数保存到另一个数组中?