Re: Sorting two arrays with one call to sort()?
On Sep 22, 3:12 pm, Ben Rudiak-Gould <br276delet...@cam.ac.uk> wrote:
John wrote:
I havetwoseparatearraysA and B. The comparison function only
depends on elements in A (keys are in A),
but the swap() function needs to swap not only A[i],A[j], but also
B[i],B[j] ; whenever it swaps A[i],A[j].
Can this be doneusinginternalsort() of C++?
I should hope so, since the main point of the STL is to decouple algorithms
from data structures. Something like this ought to work:
struct double_iterator {
T* const a; U* const b; size_t i;
struct ref {
T& p; U& q;
ref(T& p, U& q) : p(p), q(q) {}
};
ref operator*() { return ref(a[i], b[i]); }
// ...
};
inline void operator=(ref x, ref y) { x.p = y.p; x.q = y.q; }
inline bool operator<(ref x, ref y) { return x.p < y.p; }
// ...
std::sort(double_iterator(A,B,0), double_iterator(A,B,size));
I think this will be as efficient as a hand-codedsortif you have a decent
compiler.
{ signature and clc++m banner removed - please remove them yourself. -mod }
Here is as far as I got, it still doesnt work :(
#include <iostream>
using namespace std;
const int N = 10;
template < typename tA, typename tB >
struct double_iterator {
tA* a;
tB* b;
size_t i;
struct ref {
tA& p; tB& q;
ref(tA& p, tB& q) : p(p), q(q) {};
void operator=(ref y){
p= y.p; q = y.q;
};
void operator<(ref y){
return p < y.p;
};
};
ref operator*(){ return ref(a[i],b[i]); }
double_iterator(tA* _a, tB* _b, size_t _i){
a = _a;
b = _b;
i = _i;
};
};
int main(void){
int A[N];
float B[N];
for (int i = 0; i < N; ++i){
A[i] = rand(); B[i] = A[i] % 10;
cout << "\t" << A[i] << "\t" << B[i] << endl;
}
std::sort(double_iterator<int,float>(A,B,0),
double_iterator<int,float>(A,B,N));
for (int i = 0; i < N; ++i){
cout << "\t" << A[i] << "\t" << B[i] << endl;
}
return 0;
}
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]