数组C++中最大的两个

Two biggest of array C++

本文关键字:两个 C++ 数组      更新时间:2023-10-16

我有一个问题,它看起来很容易,但我不能解决它。给出了n个整数的数组。找到数组中最大的两个元素。我发现第一个找不到第二个。请帮我找第二个。

#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
int a[n];
for(int i=0;i<n;i++) {
cin>>a[i];
}
int maks=a[0];
for (int i=1;i<n;i++) {
if(a[i]>maks) {
maks=a[i];
}
}
cout << maks;
}

以下是查找数组中第二大元素的片段

#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
int *a = new int[n];
for (int i = 0; i < n; i++) {
cin >> a[i];
}
int top2element[2];
if (a[0] > a[1]) {
top2element[0] = a[0];
top2element[1] = a[1];
}
else {
top2element[1] = a[0];
top2element[0] = a[1];
}
for (int i = 2; i < n; i++) {
if (a[i] > top2element[0])
{
top2element[1] = top2element[0];
top2element[0] = a[i];
}
else if (a[i] > top2element[1]) {
top2element[1]= a[i];
}
}
cout << top2element[0]<<endl;//biggest
cout << top2element[1];//second biggest
delete a;
}

注意:如果输入流的大小未知,则动态分配内存