
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Find closest value for every element in array in C++
Here we will see how to find the closest value for every element in an array. If an element x has next element that is larger than it, and also present in the array, then that will be the greater value of that element. If the element is not present, then return -1. Suppose the array elements are [10, 5, 11, 6, 20, 12], then the greater elements are [11, 6, 12, 10, -1, 20]. As 20 has not greater value in the array, then print -1.
To solve this, we will use the set in C++ STL. The set is implemented using the binary tree approach. In binary tree always the inorder successor is the next larger element. So we can get the element in O(log n) time.
Example
#include<iostream> #include<set> using namespace std; void nearestGreatest(int arr[], int n) { set<int> tempSet; for (int i = 0; i < n; i++) tempSet.insert(arr[i]); for (int i = 0; i < n; i++) { auto next_greater = tempSet.upper_bound(arr[i]); if (next_greater == tempSet.end()) cout << -1 << " "; else cout << *next_greater << " "; } } int main() { int arr[] = {10, 5, 11, 6, 20, 12}; int n = sizeof(arr) / sizeof(arr[0]); nearestGreatest(arr, n); }
Output
11 6 12 10 -1 20
- Related Articles
- Find closest greater value for every element in array in C++
- Find closest smaller value for every element in array in C++
- Find the closest value of an array in JavaScript
- Find closest number in array in C++
- Find closest index of array in JavaScript
- Find maximum sum taking every Kth element in the array in C++
- Add every element of a masked Array with a scalar value in NumPy
- Subtract a scalar value from every element of a masked Array in NumPy
- Divide a scalar value into every element of a masked Array in NumPy
- Find last element after deleting every second element in array of n integers in C++
- Find the closest element in Binary Search Tree in C++
- JavaScript Program to Find closest number in array
- XOR every element of a masked array by a given scalar value in Python
- XOR a given scalar value with every element of a masked array in Python
- AND every element of a masked array by a given scalar value in Python

Advertisements