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 ?
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.
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.
Indexing works on Vectors, So just Acces it by using index. Similar to arrays.
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.
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.
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