如何在不C++排序的情况下找到给定向量中的第一、第二和第三高值?
How to find first, second and third highest value in a given vector without sorting in 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 等值,这段代码将不起作用,因为查找第二名和第三名的循环永远不会实现。我不知道从哪里来解决这个问题。
您可以将最高值存储在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;
}
相关文章:
- 将向量作为类>(值)<向量启动和向量<类>[值]有什么区别
- 输入较高值时的分段代码
- 较高值 n 的分割错误(例如 n=999997)
- 在 C++11 及更高版本中,有没有办法初始化初始值设定项列表中的向量?
- 布尔值向量的基于范围 for 循环
- 如何从C++中的值向量构造整数<bool>值
- 为什么int x = 01234给出x为668的外高值
- 传递右值与左值向量
- 基于C 中布尔值向量中的向量中选择对象
- 在我的Matrix4类中使用某些用户定义的运算符的操作正在返回高值的高值
- 当输入为高值时程序崩溃
- 指针向量与值向量 大内存块与小内存块的性能损失
- placeNumbers应该返回数字的顺序,以便满足布尔值向量中编码的条件
- 如何从对象指针向量创建对象值向量
- c++方法有时会返回意外的高值
- 欧拉#8项目,我不知道为什么我的代码给出了荒谬的高值
- 使用的布尔值向量比动态位集慢
- 在c++中在多个函数之间返回和赋值向量的最佳方法
- 在键向量和值向量上同时进行就地std::排序
- 如何设置int64的较低或较高值