如何排序一个数组,得到新数组,并得到新数组每个元素在原数组的下标?

ljm870605 2012-03-09 11:53:53
假如一个数组a[6]={1,1,4,2,3,2,1};用一种排序方法(最好用堆排序或归并排序等复杂度低一些的方法,因为实际的数组a很大)得到一个新的排序后的数组b[6]={1,1,1,2,2,3,4};有什么办法知道b数组中的元素在a数组中下标的位置?
...全文
184 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
hen_hao_ji 2012-03-10
  • 打赏
  • 举报
回复

#include <iostream>
#include <algorithm>
using namespace std;

struct node
{
int num;
int index;
}r[100];
bool cmp(node x, node y)
{
return x.num < y.num ? true:false;
}
int main()
{
int a[]={1, 1, 4, 2, 3, 2, 1};

int n = sizeof(a)/sizeof(int);

for (int i=0; i < n; ++i)
{
r[i].num = a[i];
r[i].index = i;
}
sort(r, r + n, cmp);

return 0;
}
RabbitLBJ 2012-03-10
  • 打赏
  • 举报
回复

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 pair<T,U>& a) const
{
return a.second;
}
};

template<class IterIn,class IterOut>
void sort_idxtbl(IterIn first,IterIn last,IterOut out)
{
multimap<IterIn,int,CompareDeref<IterIn> > v;
for(int i = 0;first != last;++i,++first)
{
v.insert(make_pair(first,i));
}
transform(v.begin(),v.end(),out,Pair2nd<IterIn,int>());
}
}


int main()
{
int ai[10] = {15,12,13,14,18,11,10,17,16,19};
cout << "----------------------" << endl;
vector<int> vecai(ai,ai + 10);
int aidxtbl[10];
Solution3::sort_idxtbl(vecai.begin(),vecai.end(),aidxtbl);
for(int i = 0;i < 10;i++)
{
cout << "i=" << i
<< ",aidxtbl[i]=" << aidxtbl[i]
<< ",ai[aidxtbl[i]]=" << ai[aidxtbl[i]]
<< endl;
}
cout << "----------------------" << endl;
cin.get();
return 0;
}

oniisama 2012-03-10
  • 打赏
  • 举报
回复
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main()
{
int a[]={1,1,4,2,3,2,1};
struct ArrayIndex
{
int value;
int index;
}element;
vector<ArrayIndex> myarray;
for(int i=0;i<sizeof(a)/sizeof(int);++i)
{
element.value=a[i];
element.index=i;
myarray.push_back(element);
}
sort(myarray.begin(),myarray.end(),[&](ArrayIndex x,ArrayIndex y){return x.value<y.value;});
for_each(myarray.begin(),myarray.end(),[&](ArrayIndex x){wcout<<x.index<<endl;});
}

64,648

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧