如何找到 n 个最大元素的索引
How to find indexes of the n greatest elements
我有一个任意类型的容器(Vector(,我想得到一个包含n个最大(或最小(元素索引的向量。
有没有标准的方法?
这正是
本周大师之一的主题 http://www.gotw.ca/gotw/073.htm
我正在报告首选的解决方案,但是,我强烈建议您阅读这篇文章(以及一般的博客(,它真的很好。
#include <vector>
#include <map>
#include <algorithm>
namespace Solution3
{
template<class T>
struct CompareDeref
{
bool operator()( const T& a, const T& b ) const
{ return *a < *b; }
};
template<class T, class U>
struct Pair2nd
{
const U& operator()( const std::pair<T,U>& a ) const
{ return a.second; }
};
template<class IterIn, class IterOut>
void sort_idxtbl( IterIn first, IterIn last, IterOut out )
{
std::multimap<IterIn, int, CompareDeref<IterIn> > v;
for( int i=0; first != last; ++i, ++first )
v.insert( std::make_pair( first, i ) );
std::transform( v.begin(), v.end(), out,
Pair2nd<IterIn const,int>() );
}
}
#include <iostream>
int main()
{
int ai[10] = { 15,12,13,14,18,11,10,17,16,19 };
std::cout << "#################" << std::endl;
std::vector<int> aidxtbl( 10 );
// use another namespace name to test a different solution
Solution3::sort_idxtbl( ai, ai+10, aidxtbl.begin() );
for( int i=0; i<10; ++i )
std::cout << "i=" << i
<< ", aidxtbl[i]=" << aidxtbl[i]
<< ", ai[aidxtbl[i]]=" << ai[aidxtbl[i]]
<< std::endl;
std::cout << "#################" << std::endl;
}
相关文章:
- 在对向量中查找元素的索引
- 当该数组的索引中没有元素时,指针指向什么?
- 如何在 STL 函数中找到传递给谓词的元素的索引?
- 如何在C++中递归地找到max元素的索引?
- 编译器(Visual C++)如何优化按索引访问矢量元素?
- 保持排序的数据结构,允许log N插入时间,并且可以返回我在log N中查找的元素的索引
- 使用推力根据索引更改某些元素的值
- 为什么 min_element() 返回最小元素的索引,而不是迭代器?
- CPtrList - 如何获取元素的索引?
- 获取结构 c++ 中元素的索引
- C++ STL 数据结构常时按索引推送/弹出/随机访问,并具有指向元素的可靠指针
- 矢量指针索引处的读取元素
- C++函数返回两个 char 数组的相同索引元素
- 特征:类似 numpy 的元素索引
- 如何在另一个数组中找到一个未排序数组的不同元素索引?
- C 无法使用嵌套环将数组的元素索引
- Opencv Mat的元素索引产生垃圾
- 在c++中,当元组的元素索引在运行时已知时,是否有可能获得该元素的类型?
- 按内容访问QVector元素索引
- C++ 矢量元素索引