简体   繁体   English

找到第二大的数字

[英]Finding a number that is second to the largest

I'd like to find the number that is second to the largest one from a list of integers. 我想从整数列表中找到倒数第二个最大的数字。 For Example if input = (-10, -47, 3, 4,100,12,200,1) then max number is 200 and the one I'd like to find is 100. 例如,如果输入= (-10, -47, 3, 4,100,12,200,1)则最大数量为200,而我想找到的最大数量为100。

Here is my program, 这是我的程序

template<typename T>
T MaxElem(T t, T s)
{
    return std::max(t, s);
}
template<typename T, typename ...A>
T MaxElem(T a, T b, A...x)
{
    return MaxElem(MaxElem(a,b), x...);
}
template<typename T>
T Second(T t1, T t2)
{
    return (t1 < t2)? t2 : t1;
}
template<typename T>
T Second(T t1, T t2, T x)
{
    return (t1 < t2) ? ((t2 == x)? t1 : t2) : t1;
}
template<typename T, typename ...args>
T Second(T t1, T t2, args...a)
{   
    return Second(Second(t1, t2, MaxElem(t1, t2, a...)), a...);
}

It outputs 200 as an incorrect result. 它输出200作为不正确的结果。

I think a simple way is below: 我认为以下是一种简单的方法:

std::sort(numbers.begin(), numbers.end());
std::reverse(numbers.begin(), numbers.end());
cout << numbers[1] ; // second largest 

Your Second needed tweaking: 您的第二个需要调整的内容:

#include <algorithm>

template<typename T>
T MaxElem(T t, T s)
{
    return std::max(t, s);
}
template<typename T, typename ...A>
T MaxElem(T a, T b, A...x)
{
    return MaxElem(MaxElem(a, b), x...);
}
template<typename T>
T Second(T t1, T t2)
{
    return (t1 < t2) ? t1 : t2; //here
}
template<typename T>
T Second(T t1, T t2, T x)
{
    return Second(t1, x) < Second(t2, x) ? (t2 == x ? t1 : t2) : (t1 == x ? t2 : t1); //and here
}
template<typename T, typename ...args>
T Second(T t1, T t2, args...a)
{
    return Second(Second(t1, t2, MaxElem(t1, t2, a...)), a...);
}
int main()
{   

    std::cout << Second(-10, -47, 3, 4, 100, 12, 200);

    return 0;
}

Returns 100 返回100

You can use std::nth_element function: 您可以使用std :: nth_element函数:

#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>

int main() {
    std::vector<int> numbers{ -10, -47, 3, 4, 100, 12, 200, 1 };
    std::nth_element(numbers.begin(), numbers.begin() + 1, numbers.end(), std::greater<int>());
    std::cout << "The second largest element is " << numbers[1] << '\n';
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM