gpt4 book ai didi

C++ vector 下标超出范围第 1201 行

转载 作者:太空宇宙 更新时间:2023-11-04 14:43:38 25 4
gpt4 key购买 nike

所以我不得不将 n 个实数写入 vector ,然后打印其中最大的一个。

#include <iostream>
#include <vector>
using namespace std;

void printMax(vector<double>);

int main()
{
vector<double> vct;
double n;

while(cin >> n)
vct.push_back(n);

printMax(vct);
return 0;
}

void printMax(vector<double> x)
{
int max;

for(int i = 1; i < x.size(); i++)
{
if(x[i] > x[i - 1]) max = x[i];
else continue;
}

cout << "Max = \t" << max << endl;
}

当我启动这个程序时,它允许我输入数字,但是当我按下 ctrl+z 并输入它时,它崩溃了,并说:vector subscript out of the range line: 1201。我认为问题出在 void printMax 部分。

最佳答案

您必须使用 i = 1 开始以下循环:

for (int i = 1; i < x.size(); i++){
if (x[i] > x[i - 1])
max = x[i];
// else continue superfluous
}

因为如果i0 , i - 1将是负数(或 unsigned int 的最大值)。在这种情况下,这可能不是有效索引。

另外,你为什么要使用 int对于所说的实数?

事实上,有一种更简单的方法可以找到 vector 的最大元素。它不涉及两个连续元素的比较,而是比较当前的max。针对每个元素。改进你的算法,或者使用 std::max_element .

当我写改进时,我的意思实际上是纠正

关于C++ vector 下标超出范围第 1201 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33977594/

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