Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,970 questions

51,912 answers

573 users

How to find the K largest element in a vector with C++

1 Answer

0 votes
#include <iostream>
#include <vector>
#include <queue>

int findKLargest(std::vector<int> const &v, int K) {
    if (v.size() < K) {
        return -1;
    }
 
    std::priority_queue<int, std::vector<int>, std::greater<int>> pq(v.begin(), v.begin() + K);
    
    for (int i = K; i < v.size(); i++) {
        if (v[i] > pq.top()) {
            pq.pop();
            pq.push(v[i]);
        }
    }
 
    return pq.top();
}
 
int main()
{
    std::vector<int> v = { 100, 88, 98, 80, 50, 12, 35, 70, 60, 97, 85, 89  };
    int K = 4;
 
    std::cout << findKLargest(v, K);
}





/*
run:
 
89
 
*/

 



answered May 12, 2022 by avibootz
edited May 12, 2022 by avibootz

Related questions

1 answer 117 views
1 answer 126 views
1 answer 162 views
2 answers 133 views
2 answers 123 views
1 answer 94 views
...