如何在不C++排序的情况下找到给定向量中的第一、第二和第三高值?

How to find first, second and third highest value in a given vector without sorting in C++?

本文关键字:高值 向量 C++ 排序 情况下      更新时间:2023-10-16

这是我为代码所做的

int maxIndex = 0; int secPlace = 0; int minIndex = 0; 
for(int k = 0; k < w.size(); k++){  //Finding First Place
if(w.at(k) > w.at(maxIndex)) {                                       
maxIndex = k;                                                   
}
}
for(int a = 0; a < w.size(); a++){ //Finding Second Place
if( a!= maxIndex && w.at(secPlace) < w.at(a)){
secPlace = a; 
}
}
for(int b = 0; b < w.size(); b++){   //Finding third place
if(b != maxIndex && b != secPlace && w.at(minIndex) < w.at(b)){
minIndex = b;
}

我知道如果我让用户输入 10、8、6 等值,这段代码将不起作用,因为查找第二名和第三名的循环永远不会实现。我不知道从哪里来解决这个问题。

您可以将最高值存储在vector中,将较高的值插入该vector并将其限制为大小 3 :

#include <vector>
using namespace std;
int main()
{
vector<int> w, m;
for (auto a : w)
{
bool added = false;
for (auto it = m.begin(); it != m.end(); it++)
{
if (a > *it)
{
added = true;
m.insert(it, a);
if (m.size() > 3)
{
m.resize(3);
}
break;
}
}
if (!added && m.size() < 3)
{
m.push_back(a);
}
}
return 0;
}