I need to get the rank (the positional index+1) of an element for containers in C++ like vector
or list
. Is there a convenient way of doing so? I could have done testing based on nth_element
in order to find the rank. Or I could sort and do binary search to find the rank. But all of these do not seem very efficient in the worst-case. I'd like to get O(lgn) complexity, and done with STL algorithms if possible.
Rank of an element E in an array A is the number of elements of A less than E plus the number of elements equal to E appearing to the left of E.
To compute the rank of the element first make a copy of given arr[] then sort that copied array in ascending order. Then traverse in the copied array and put their rank in HashMap by taking a rank variable.
Follow the steps below to solve the problem: find(): Used to find the position of element in the vector. Subtract from the iterator returned from the find function, the base iterator of the vector . Finally return the index returned by the subtraction.
If your container has random access iterators (e.g. vector) and is sorted, you can use the std::lower_bound()
algorithm to get an elements index in O(log n) complexity. For example:
std::vector<int> v({10,20,30,30,20,10,10,20});
std::sort(v.begin(), v.end());
auto iter = std::lower_bound(v.begin(), v.end(), 20);
std::cout << "index " << int(iter - v.begin()) << std::endl;
(I'm using C++11 syntax to keep the code short, but you should get the idea).
Note that you can insert elements to a vector in a sorted way, so you don't need to sort before finding the index.
It seems very unlikely that you will find something more efficient than linear search here. The worst case must necessarily be that you compare all elements with what you search for - and that is exactly what linear search gives you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With