如何找到向量中5个最大元素的索引? [英] How to find indexes of 5 the biggest elements in vector?
问题描述
如何找到向量中 5 个最大元素的索引?例如 std::vector
如何找到 5 个最大值的索引而不改变原始向量?
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 ?
推荐答案
std::partial_sort( v.begin(), v.begin()+5, v.end() )
sorts某种方式的向量,其中 5 个最小值被排序并位于 v
的开头.其余部分未排序.
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.
由于您想要索引并保留原始索引:
用 0..n-1 中的数字填充一个新向量,并提供一个比较函数,它执行 v[a] >v[b]
而不是 a >b
:
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]
包含索引.
这篇关于如何找到向量中5个最大元素的索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!