Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/148.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 在数组中查找某个最高值_C++_Arrays - Fatal编程技术网

C++ 在数组中查找某个最高值

C++ 在数组中查找某个最高值,c++,arrays,C++,Arrays,我必须在数组中找到某个最高值(例如第五个最高值) 我写了一篇短文,但花的时间太长了。有没有办法加快速度 int tab[100]; // cin tab; int position; cin>>position; // for example i need to find fifth highest // value in an array. int temp=0; sort( tab, tab + 100, g

我必须在数组中找到某个最高值(例如第五个最高值)

我写了一篇短文,但花的时间太长了。有没有办法加快速度

    int tab[100];
    // cin tab;

    int position;
    cin>>position;
    //  for example i need to find fifth highest
    // value in an array.

    int temp=0;

    sort( tab, tab + 100, greater <int>() );

    for(int y=0; y<100; ++y)
    {
        if (tab[y]==tab[y+1])
            continue;
        else
        {
            temp++;
            if(temp==position)
                cout<<tab[y];
        }
    }
int选项卡[100];
//cin标签;
内部位置;
cin>>位置;
//例如,我需要找到第五高
//数组中的值。
内部温度=0;
排序(制表符,制表符+100,更大());

对于(int y=0;y,正如有人在评论中提到的,如果您不想自己编写算法,那么使用std:nth_元素是一种方法

如果你想自己写,你可以看看这篇文章:

它解释了如何在二进制搜索树中查找第n个元素

二进制搜索树的信息可在维基百科上找到:


这将为您提供一个良好的起点。

可能会大大加快速度。而且,由于您在输入后调用了排序,因此您正在计时排序+算法。当所有元素都相同时,您就有了UB(
y+1
超出范围)。一旦找到值,您可以
中断
。OP似乎可以管理重复的值,因此
std::nth_元素
的使用并不是那么简单。