在STL中使用pair根据另一个数组对数组进行排序

2021年5月16日17:11:14 发表评论 1,558 次浏览

我们得到两个数组。我们需要对另一个数组进行排序。

例子:

Input : 2 1 5 4 9 3 6 7 10 8
        A B C D E F G H I J

Output : 1 2 3 4 5 6 7 8 9 10 
         B A F D C G H J E I 
Here we are sorting second array
(a character array) according to 
the first array (an integer array).

我们在下面的帖子中讨论了不同的方式。

根据另一个数组定义的顺序对数组进行排序

在这篇文章中, 我们着重于使用对C ++的STL中存在的容器。

为了完成我们的任务, 我们将对两个数组中的各个元素进行配对, 然后简单地使用sort函数。要注意的重要一点是, 对中的第一个元素应该来自要执行排序的数组。

//Sort an array according to 
//other using pair in STL.
#include <bits/stdc++.h>
using namespace std;
  
//Function to sort character array b[]
//according to the order defined by a[]
void pairsort( int a[], char b[], int n)
{
     pair<int , char> pairt[n];
  
     //Storing the respective array
     //elements in pairs.
     for ( int i = 0; i <n; i++) 
     {
         pairt[i].first = a[i];
         pairt[i].second = b[i];
     }
  
     //Sorting the pair array.
     sort(pairt, pairt + n);
      
     //Modifying original arrays
     for ( int i = 0; i <n; i++) 
     {
         a[i] = pairt[i].first;
         b[i] = pairt[i].second;
     }
}
  
//Driver function
int main()
{
     int a[] = {2, 1, 5, 4, 9, 3, 6, 7, 10, 8};
     char b[] = { 'A' , 'B' , 'C' , 'D' , 'E' , 'F' , 'G' , 'H' , 'I' , 'J' };
                           
     int n = sizeof (a) /sizeof (a[0]);
      
     //Function calling
     pairsort(a, b, n);
  
     for ( int i = 0; i <n; i++)
         cout <<a[i] <<" " ;
     cout <<endl;
  
     for ( int i = 0; i <n; i++)
         cout <<b[i] <<" " ;
          
     return 0;
}

输出如下:

1 2 3 4 5 6 7 8 9 10 
B A F D C G H J E I

如果发现任何不正确的地方, 或者想分享有关上述主题的更多信息, 请写评论。

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: