如何分别对两个不同的数组进行排序 [英] how to sort two different arrays correspondingly
本文介绍了如何分别对两个不同的数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
请解决以下问题!
假设我们有类似的代码;
Please solve my following problem!
suppose we have a code like;
struct team
{
int runs[15];
char *name[15];
} ind,pak,aus;
// now first murge these int arrays in a single array
int d[45];
for(int i=0; i<15; i++)
{
d[i]=pak.runs[i];
d[15+i]=ind.runs[i];
d[30+i]=aus.runs[i];
}
现在,我可以使用任何方法对它们进行排序,
最终我得到了排序后的值,但是我需要这些运行相邻的名称.
喜欢;
pak.runs[5]
在排序后放置在d[14]
上,那么如何在排序后在pak.name[5]
显示相应的名称?
我希望你能理解我的问题...
请帮助我!
Now , I sort them using any method,
finally I get sorted values but I need the names adjacent to these runs.
like;
pak.runs[5]
is placed at d[14]
after sorting , then how can i display the corresponding name at pak.name[5]
after sorting?
I hope you understand my question...
Please help me!
推荐答案
作为快速解决方案,
将所有3x15名称复制到上述for循环的单个数组中.
在对d [45]数组进行排序时,根据排序索引交换name []值(我不知道您要使用哪种算法进行排序,但是您将通过索引交换d []值,同时交换值).我这里没有考虑任何性能问题.
As a quick solution,
Copy all 3x15 names into single array in the above for loop.
While sorting d[45] array, exchange the name[] values according to the sorting index(i do not know which algorithm you are using for sorting but you will exchange d[] values through indexes, at the same time you exchange the values).I am not considering any performance issues here.
如何使用STL呢?您可以使用std::list<std::string>
类,该类具有方法sort
.
—SA
How about using STL instead? You can usestd::list<std::string>
class, which has the methodsort
.
—SA
这可能对您有所帮助.
在对数组进行排序之前,应先填充名称数组,如
This may help you.
Before sorting of array you should fill name array like,
char *dn[45];
for(int j=0; j<15; j++)
{
dn[j]=pak.name[j];
dn[15+j]=ind.name[j];
dn[30+j]=aus.name[j];
}
现在,您的排序逻辑可能会有所不同,但使用线性排序却可以做到相同,
now your sorting logic may differ but with linear sorting with do same,
void selectionSort(int arr[],char namearray[], int size)
{
int indexOfMin, pass, j;
for (pass = 0; pass < size - 1; pass++)
{
indexOfMin = pass;
for (j = pass + 1; j < size; j++)
if (arr[j] < arr[indexOfMin])
indexOfMin = j;
swap(arr[pass], arr[indexOfMin]);
swapName(namearray[pass],namearray[indexOfMin]);
}
}// end selectionSort()
void swap(int& x, int& y)
{
int temp;
temp = x;
x = y;
y = temp;
}// end swap()
void swapName(char& x, char& y)
{
int temp;
temp = x;
x = y;
y = temp;
}// end swapNames
这篇关于如何分别对两个不同的数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文