Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the rank of an element in vector in C++

Tags:

c++

stl

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.

like image 677
Qiang Li Avatar asked Jan 19 '12 00:01

Qiang Li


People also ask

How do you find the rank of an element?

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.

How do you find the rank of an element in an array?

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.

How do you find the index number of an element in a vector?

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.


2 Answers

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.

like image 155
drrlvn Avatar answered Sep 19 '22 19:09

drrlvn


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.

like image 35
Johan Kotlinski Avatar answered Sep 20 '22 19:09

Johan Kotlinski