Sorting two corresponding arrays

后端 未结 4 1736
野性不改
野性不改 2020-11-27 16:45

I have this code here that has two arrays. It sorts arr[], so that the highest value will be in index 0. Now the second array arr1[] contai

4条回答
  •  长情又很酷
    2020-11-27 17:49

    You need to combine them together and then sort the combined pair and then un-combine the pairs.

    int arr[ 5 ] = { ... };
    string arr1[ 5 ] = { ... };
    pair pairs[ 5 ];
    
    for ( int i = 0; i < 5; ++i )
      pairs[ i ] = make_pair( arr[ i ], arr1[ i ] );
    
    sort( pairs.begin(), pairs.end() );
    
    for ( int i = 0; i < 5; ++i )
    {
      arr[ i ] = pairs[ i ].first;
      arr1[ i ] = pairs[ i ].second;
    }
    

    Really though, if arr and arr1 are related then they should be stored as the pair (or at least a custom struct) anyway. That way you don't need to use this as an intermediate step.

提交回复
热议问题