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

51,767 answers

573 users

How to find the floor and ceiling of the value N in an unsorted vector with C++

1 Answer

0 votes
#include <iostream>
#include <vector>
#include <climits> // For INT_MIN and INT_MAX
 
void findFloorAndCeil(const std::vector<int>& vec, int N, int& floorval, int& ceilval) {
    floorval = INT_MIN; // Initialize floorval to the smallest possible value
    ceilval = INT_MAX;  // Initialize ceilval to the largest possible value
 
    for (int num : vec) {
        if (num <= N && num > floorval) {
            floorval = num; // Update floorval if num is closer to N
        }
        if (num >= N && num < ceilval) {
            ceilval = num; // Update ceilval if num is closer to N
        }
    }
 
    // If no valid floorval or ceilval is found, set them to a special value
    if (floorval == INT_MIN) floorval = -1; // No floorval exists
    if (ceilval == INT_MAX) ceilval = -1;  // No ceilval exists
}
 
int main() {
    std::vector<int> vec = {4, 10, 8, 2, 6, 9, 1};
    int N = 5; // Value to find floor and ceil
 
    int floorval, ceilval;
    findFloorAndCeil(vec, N, floorval, ceilval);
 
    std::cout << "floor: " << (floorval == -1 ? "None" : std::to_string(floorval)) << std::endl;
    std::cout << "ceil: " << (ceilval == -1 ? "None" : std::to_string(ceilval)) << std::endl;
}
 
 

/*
run:
 
floor: 4
ceil: 6
 
*/

 



answered Nov 7, 2025 by avibootz
edited Nov 8, 2025 by avibootz
...