向量中的最大值

Max value in a vector

本文关键字:最大值 向量      更新时间:2023-10-16

我正在尝试计算 int[] 中的最大值。下面的程序崩溃了,但我不明白为什么。Test类有问题吗?谢谢。

class Max {
int *max;
public:
Max() {
max = NULL;
}
~Max() {
if (max)
delete max;
}
void compute(int N[], int n) {
this->~Max();
max = new int(N[0]);
for (int i = 0; i < n; i++)
if (*max < N[i])
*max = N[i];
}
void print() {
cout << "Max= " << *max << endl;
}
};
class Test {
public:
static Max& getMax(int N[], int n) {
Max m;
m.compute(N, n);
return m;
}
};

void main() {
int N[] = { 8,9,7,8,10,6 };
Test::getMax(N, sizeof(N) / sizeof(int)).print();
}

最好的方法是将std::vector/std::arraystd::max_element一起使用。我建议首先学习使用 stl 容器和算法的现代 c++,然后你可以了解低级功能。

但是为了让您了解以下代码中的错误:

  1. 使用nullptr而不是NULL

    Max() {
    max = nullptr;
    }
    
  2. 不要调用析构函数

    this->~Max();
    
  3. 不返回对局部变量的引用

    static Max& getMax(int N[], int n) { // 
    Max m;
    m.compute(N, n);
    return m;
    }
    
  4. 不要使用using namespace std;

  5. 请记住为每个new调用一个delete,为每个new []调用一个delete[]。(尽可能避免newnew []deletedelete[])

  6. 您不需要用于max的指针。int max;在你稍微熟练你的代码之后也可以工作。

>当然你可以使用std::vectorstd::max_element但代码的真正问题(除了许多错误)是它有多复杂。用C++编程比你想象的要容易。

下面介绍如何以简单的方式编写相同的代码,这个简单的任务不需要任何类。

#include <iostream>
using namespace std;
int compute(int N[], int n) {
int max = N[0];
for (int i = 0; i < n; i++)
if (max < N[i])
max = N[i];
return max;
}
void print(int max) {
cout << "Max= " << max << endl;
}
int main() {
int N[] = { 8,9,7,8,10,6 };
print(compute(N, sizeof(N) / sizeof(int)));
}

未经测试的代码。

量中的最大值

那不是向量。这是一个数组。整数的向量称为std::vector<int>。您可能应该使用一个。

void compute(int N[], int n) {
this->~Max();

被称为*this的对象在此行之后正式死亡。除了取消分配内存或使用放置 new 在其尸体上构建另一个实例之外,您不能合法地对它做任何事情。

實際上所做的 - 不是這些事情 - 是非法和不道德的。

据我所知,在这里有一个指针(并重新/取消/分配它)甚至没有实现任何目标。如果您可以只编写int max;并避免动态分配,请执行此操作。

static Max& getMax(int N[], int n) {
Max m;
m.compute(N, n);
return m;
}

返回对临时的引用也是非法的。也

  • 按值返回m(如果您希望动态分配正常工作,则需要编写适当的复制和移动构造函数和赋值运算符,尽管只是删除它会节省大量工作和错误)
  • 或者只是返回计算出的最大值并将其打印在外面(没有明显的原因Max类应该耦合到std::cout)。

综上所述,我按偏好顺序的建议是:

  1. 使用std::vector<int>std::max_element
  2. 如果您必须编写自己的版本,max仍然应该是一个返回结果的函数,而不是将对象突变为...存储结果以备后用?所以:

    int compute_max(int const *n, int nlen) {
    // handle corner cases
    if (nlen < 1) return std::numeric_limits<int>::min();
    int result = n[0];
    for (int i = 1; i < nlen; i++)
    if (result < n[i])
    result = n[i];
    return result;
    }
    
  3. 如果你必须有一个有状态的Max类(这对我来说仍然是一个非常奇怪的设计),只需删除动态分配

  4. 如果必须具有动态分配,则仍需要停止显式调用析构函数,需要实现复制和移动构造函数/赋值运算符,并且理想情况下应使用std::unique_ptr<int>而不是原始指针

无论您喜欢哪种Max实现(我想强调的是,选项 3 和 4 是非常遥远的第三和第四最佳选项,仅在非常不正常或人为的条件下使用),您都不得返回对getMax()中局部变量的引用。或者其他任何地方,显然。