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,922 questions

51,855 answers

573 users

How to find the second biggest number in a vector with C++

1 Answer

0 votes
#include <iostream>
#include <limits.h>
#include <vector>
 
int findSecondLargest(const std::vector<int>& vec) {
    if (vec.size() < 2) {
        std::cerr << "Array must contain at least two elements" << std::endl;
        return INT_MIN; 
    }
 
    int first = INT_MIN, second = INT_MIN;
 
    for (int num : vec) {
        if (num > first) {
            second = first;
            first = num;
        } else if (num > second && num != first) {
            second = num;
        }
    }
 
    return second;
}
 
int main() {
    std::vector<int> vec = {42, 7, 93, 58, 29, 61, 17, 84, 36, 75};
    int secondLargest = findSecondLargest(vec);
 
    if (secondLargest != INT_MIN) {
        std::cout << "The second largest number is: " << secondLargest << std::endl;
    }
}
 
 
/*
run:
 
The second largest number is: 84
 
*/

 



answered Jan 19, 2025 by avibootz
edited Jan 19, 2025 by avibootz
...