首页 > 解决方案 > 如何在给定向量中找到第一个、第二个和第三个最大值而不在 C++ 中排序?

问题描述

这是我为代码所做的

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 之类的值,则此代码将不起作用,因为用于查找第二名和第三名的循环永远不会实现。我不知道从这里去哪里来解决这个问题。

标签: c++

解决方案


您可以将最高值存储在 a 中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;
}

推荐阅读