简体   繁体   English

数组中第 K 个最小的元素

[英]Kth smallest element in a array

I was writing this code for finding Kth smallest element in array where l= starting index and r = ending index is given to us as input parameter in function.我正在编写此代码以查找数组中的第 K 个最小元素,其中 l= 起始索引和 r = 结束索引作为 function 中的输入参数提供给我们。

class Solution{
    public:
    int kthSmallest(int arr[], int l, int r, int k) {
        //code here
        arr.sort(l,l+r+1);
        int count =1,i=1,var =0;
        while(count<=k)
        {
            var = arr[i];
            count++;
            i++;
        }
        return var;
    }
};

I tried to use sort function in my code but this code is giving error in my sort function,given below which is not understood by me.我尝试在我的代码中使用排序 function 但此代码在我的排序 function 中给出错误,下面给出我不理解的。

prog.cpp: In member function int Solution::kthSmallest(int*, int, int, int): prog.cpp: 在成员 function int 解决方案::kthSmallest(int*, int, int, int):

prog.cpp:18:13: error: request for member sort in arr, which is of non-class type int* prog.cpp:18:13:错误:arr 中的成员排序请求,它是非类类型 int*

     arr.sort(l,l+r+1);
         ^

In C++, arrays like arr are not objects, so they have no members like sort that you can access using the dot operator.在 C++ 中,arrays 等arr不是对象,因此它们没有可以使用点运算符访问的类似sort的成员。

Instead, try using std::sort from the <algorithm> header:相反,请尝试使用<algorithm> header 中的std::sort

#include <algorithm>

std::sort(arr + l, arr + r + 1);

This example assumes that:此示例假设:

  • l is the leftmost index you're sorting. l是您要排序的最左边的索引。
  • r is the rightmost index. r是最右边的索引。
  • both l and r are valid indices for arr . lr都是arr的有效索引。

arr is type int * , so a primitive type and a primitive type don't have any member function. arrint *类型,因此原始类型和原始类型没有任何成员 function。 So arr don't have any sort() member function, so it cause an error.所以arr没有任何sort()成员 function,所以会导致错误。

If you want to sort arr , use std::sort from <algorithm> .如果要对arr进行排序,请使用std::sort from <algorithm>

std::sort(arr + l, arr + r + 1);

Another way is to use the std::nth_element algorithm, it will give you the element at the position in the array if the array where sorted.另一种方法是使用std::nth_element算法,如果数组排序,它将为您提供数组中 position 处的元素。 To use it you need iterator so you will have to convert your C array arr[] into a std::array if you don't want heap allocation or a std::vector if you want to be more flexible.要使用它,您需要迭代器,因此如果您不想要堆分配,则必须将 C 数组arr[]转换为std::array ;如果您想要更灵活,则必须转换为std::vector

Note: if you use C++ 20 you can use std::ranges::nth_element注意:如果你使用 C++ 20 你可以使用std::ranges::nth_element

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

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