Binding arrays

Hello everyone,

I'm writing a simple electrical circuit simulator and came across some logic I just can't get done with.
Problem's the following: I've got a couple of arrays of the same size and type that are defined by user input, both their values and sizes, and I'd like to bind their values to each other, like...

array_size=4

array1[0]=7
array1[1]=16
array1[2]=3
array1[3]=9

array2[0]=5000
array2[1]=-1500
array2[2]=-12000
array2[3]=6500

in a way that if the first array is sorted, the second one is altered accordingly, as in:

array1[0]=3
array1[1]=7
array1[2]=9
array1[3]=16

array2[0]=-12000
array2[1]=5000
array2[2]=6500
array2[3]=-1500

I've been thinking about this for some time already but I can't solve it anyhow.

Any help would be much appreciated.
Use standard container std::map with keys - values of the frist array.
Last edited on
Did you write your own sorting method? If so, just make sure the Swap method swaps both arrays:
1
2
3
4
5
6
7
void Swap(array& a, array& b, const int i, const int j) {
     int atemp = a[i], btemp = b[i];
     a[i] = a[j];
     b[i] = b[j];
     a[j] = atemp;
     b[j] = btemp;
}


If you're using a built-in sort (or some other blackbox sorting code), it might be easier to actually link the items by wrapping them in a struct, and then sorting an array of objects:

1
2
3
4
5
6
7
8
9
struct myVals {
    val1; // Holds "array1" value
    val2; // Holds "array2" value
    bool operator<(const myVals& rhs) { return val1 < myVals.val1; }
}

myVals values[4];
// initialization code goes here
std::sort(values, values+4); // Default sort uses i < j predicate 


Use one array containing both values? Use a std::pair or a std::tuple, perhaps?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
constexpr int array_size = 4 ;
std::pair<int,int> array[array_size] = { {}, {}, {3,12000}, {9,6500} } ;

array[0] = std::make_pair(7,5000) ;
array[1] = std::make_pair(16,1500) ;
// etc.

for( const auto& p : array ) std::cout << p.second << ' ' ;
std::cout << '\n' ;

std::sort( std::begin(array), std::end(array) ) ;

for( const auto& p : array ) std::cout << p.second << ' ' ;
std::cout << '\n' ;



I was doing it with qsort.

Thank you all for the replies, I'll try out your suggestions.

edit:

I looked for the sorting code breakdown and modified it for double swapping, works just fine.

Thanks again for the help.
Last edited on
Topic archived. No new replies allowed.