c++ - 如何在给定向量中找到第一个、第二个和第三个最大值而不在 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 之类的值,则此代码将不起作用,因为用于查找第二名和第三名的循环永远不会实现。我不知道从这里去哪里来解决这个问题。
解决方案
您可以将最高值存储在 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;
}
推荐阅读
- rxjs - 为什么 rxJs api 中存在不对称性
- c# - 将 JSON 中的数组转换为列表
- matlab - BLE模块RN4871无法与Matlab连接
- flutter - 颤动的tflite对象检测在物理设备上不起作用
- django - 更新通过 ForeignKey 连接的模型
- mongodb - MongoDB聚合双重查找和管道
- python - django cache_page 如何设置版本
- c# - Discord.Net 角色不会在机器人中更新
- python - 如何处理买卖历史csv
- ruby-on-rails - 如何在 .inky Action Mailer 模板中放置一个按钮(和链接)?