Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find indexes of 5 the biggest elements in vector?

Tags:

c++

stl

How to find indexes of 5 the biggest elements in vector ? For example std::vector<int> how to find indexes of 5 biggest values but not to change original vector ?

like image 761
Damir Avatar asked Sep 17 '12 20:09

Damir


People also ask

How do you find the maximum element index of a vector?

Approach: Min or Minimum element can be found with the help of *min_element() function provided in STL. Max or Maximum element can be found with the help of *max_element() function provided in STL.

How do you find the index element of a vector?

Access an element in vector using vector::at() reference at(size_type n); reference at(size_type n); reference at(size_type n); It returns the reference of element at index n in vector.

Can you index into a vector?

Indexing works on Vectors, So just Acces it by using index. Similar to arrays.

How do I get indices of N maximum values in a NumPy array?

For getting n-largest values from a NumPy array we have to first sort the NumPy array using numpy. argsort() function of NumPy then applying slicing concept with negative indexing. Return: [index_array, ndarray] Array of indices that sort arr along the specified axis.


1 Answers

std::partial_sort( v.begin(), v.begin()+5, v.end() ) sorts a vector in a way, that the 5 smallest values are sorted and at the beginning of v. The rest is left unsorted.

Since you want the indices and keep the original:
Fill a new vector with numbers from 0..n-1 and supply a comparison function that does v[a] > v[b] instead of a > b:

struct Comp{
    Comp( const vector<int>& v ) : _v(v) {}
    bool operator ()(int a, int b) { return _v[a] > _v[b]; }
    const vector<int>& _v;
}

vector<int> vx;
vx.resize(v.size());
for( int i= 0; i<v.size(); ++i ) vx[i]= i;
partial_sort( vx.begin(), vx.begin()+5, vx.end(), Comp(v) );

vx[0..4] contains the indices.

like image 173
rtlgrmpf Avatar answered Sep 20 '22 05:09

rtlgrmpf