歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> C++數組排序怎麼返回數值在原數組中的下標

C++數組排序怎麼返回數值在原數組中的下標

日期:2017/3/1 9:08:57   编辑:Linux編程

數組排序返回數值在原數組中的下標在matlab中根本就不是問題,一個sort函數解決:

[B,IX] = sort(A,...)

其中A為排序前的數組,B為排序後的數組,IX為排序後的下標。

可在C++中就沒有這麼簡單了,找遍了所有可能的函數,都沒有發現能實現這個功能的。於是自己寫一個,供大家參考。基本思路是:把數值(value)和下標(index)封裝成一個結構體,當數值排序時,其下標也跟著跑。

代碼如下:

#include
#include
using namespace std;

struct node
{
int value;
int index;
};
bool cmp(struct node a, struct node b)
{
if(a.value < b.value)
{
return true;
}
return false;
}

int main(){
node* a=new node[3];
a[0].index=0;
a[1].index=1;
a[2].index=2;
a[0].value=20;
a[1].value=10;
a[2].value=30;
sort(a,a+3,cmp);
for(int i=0;i<3;i++){
cout<<a[i].value<<" "<<a[i].index<<endl;
}
delete [] a;
return 0;
}

程序輸出為:

Copyright © Linux教程網 All Rights Reserved