gpt4 book ai didi

c++ - 同时最小值和最大值

转载 作者:太空狗 更新时间:2023-10-29 23:30:29 25 4
gpt4 key购买 nike

我尝试实现一种算法,该算法将在给定数组中搜索最小和最大元素,并使用了 Cormen 的算法简介 中的思想。我的代码编译并开始工作,输出生成的随机数组,然后很长一段时间什么都不做。为什么会这样?

代码是这样的:

// fast min and max --cormen exercise 1.cpp: entry point
//implemented from a verbal description in cormen's book, p 243

#include "stdafx.h"
#include <vector>
#include <ctime>
#include <cstdlib>
#include <iostream>

struct min_and_max
{
int min, max;
};


min_and_max find_min_and_max(std::vector<int>& A)
{
int n = A.size();
int min, max;
if (n%2 == 1)
min = max = A[0];
if (n%2 == 0)
if (A[0] < A[1])
{
min = A[0];
max = A[1];
}
else
{
min = A[1];
max = A[0];
}
for(int i = 2; i < A.size(); (i + 2))
{
if (A[i] < A[i+1])
{
if (min > A[i])
min = A[i];
if (max < A[i+1])
max = A[i+1];
}
else
{
if (min > A[i+1])
min = A[i+1];
if (max < A[i])
max = A[i];
}
}
min_and_max result;
result.min = min;
result.max = max;

return result;
}

int main()
{
std::srand(std::time(0));
std::vector<int> A(10);
for (auto i = 0; i < A.size(); i++)
{
A[i] = rand() % 1000;
std::cout << A[i] << " ";
}
std::cout << std::endl; //IT GOES AS FAR AS THIS
std::cout << "The array has been analyzed; its' minimum is " << find_min_and_max(A).min << "and its' maximum is " << find_min_and_max(A).max << std::endl;

return 0;
}

最佳答案

 for(int i = 2; i < A.size(); (i + 2))

i + 2不会改变i的值,你需要使用i += 2

关于c++ - 同时最小值和最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19368539/

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