向量中的最大值
Max value in a vector
我正在尝试计算 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::array
与std::max_element
一起使用。我建议首先学习使用 stl 容器和算法的现代 c++,然后你可以了解低级功能。
但是为了让您了解以下代码中的错误:
-
使用
nullptr
而不是NULL
Max() { max = nullptr; }
-
不要调用析构函数
this->~Max();
-
不返回对局部变量的引用
static Max& getMax(int N[], int n) { // Max m; m.compute(N, n); return m; }
-
不要使用
using namespace std;
-
请记住为每个
new
调用一个delete
,为每个new []
调用一个delete[]
。(尽可能避免new
、new []
、delete
和delete[]
) -
您不需要用于
max
的指针。int max;
在你稍微熟练你的代码之后也可以工作。
>当然你可以使用std::vector
和std::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
)。
综上所述,我按偏好顺序的建议是:
- 使用
std::vector<int>
和std::max_element
如果您必须编写自己的版本,
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; }
如果你必须有一个有状态的
Max
类(这对我来说仍然是一个非常奇怪的设计),只需删除动态分配- 如果必须具有动态分配,则仍需要停止显式调用析构函数,需要实现复制和移动构造函数/赋值运算符,并且理想情况下应使用
std::unique_ptr<int>
而不是原始指针
无论您喜欢哪种Max
实现(我想强调的是,选项 3 和 4 是非常遥远的第三和第四最佳选项,仅在非常不正常或人为的条件下使用),您都不得返回对getMax()
中局部变量的引用。或者其他任何地方,显然。
- 以C++递归方式查找向量中的最大值
- C++ - 如何在结构向量中找到结构体一个成员的最大值?
- 我的 If Else 语句无法在向量 (C++) 中提供最大值
- 如何修复错误:使用向量查找最小值和最大值进行合并排序
- 求长向量的最小值和最大值
- 在二维向量的每一列中查找最大值
- 向量中的最大值
- 从向量中提取最小值、最大值和中位数的最有效方法是什么
- 在向量向量中找到 Point3f 的最大值
- SSE2 内部函数 - 找到两个无符号短向量的最大值
- 使用算法查找自定义数据向量中的最大值和最小值
- 找到两个向量数组的组合,该数组的总和是 c++ 中所有其他组合的最大值
- 如何在不使用min_element C++的情况下找到向量中的最小值和最大值<double>
- 获取向量<float>中 k 个最大值的 indize 的有效方法
- 将向量用于负最大值算法 c++ 的问题
- 求向量的奇数位置最大值(以C++为单位)
- 在对象向量中查找最大值
- 一个模板函数,用于获取向量中的最大值及其相应的索引
- 如何找到向量的统计量?最大值/最小值、模式、中位数、平均值
- 从向量向量中的列中获取最小值和最大值