1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
|
#include <iostream>
#include <vector>
#include <cassert>
#include <cmath>
#include <tuple>
#include <algorithm>
#include <iomanip>
int main()
{
std::vector<int> a { 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 } ;
std::vector<double> b { 100, 101, 102, 103, 104, 105, 106, 107, 108, 109 } ;
std::vector<double> c { 6, 2, 4, 0, 8, 7, 1, 3, 5, 9 } ;
const auto print_vec = [] ( const auto& vec )
{ for( auto v : vec ) std::cout << std::setw(4) << v ; std::cout << '\n' ; } ;
print_vec(a) ;
print_vec(b) ;
print_vec(c) ;
// sort a, b, c on c.
// invariant: a, b and C are of he same size
// invariant: c does not contain NaN
assert( a.size() == b.size() && b.size() == c.size() ) ;
assert( std::none_of( c.begin(), c.end(), [] ( auto n ) { return std::isnan(n) ; } ) ) ;
{
// create a temporary vector of tuples:
// tuples contain corresponding elements from c, a, b
std::vector< std::tuple<double,int,double> > temp ;
for( std::size_t i = 0 ; i < a.size() ; ++i ) temp.emplace_back( c[i], a[i], b[i] ) ;
std::sort( std::begin(temp), std::end(temp) ) ; // sort the tuples in the temporary vector
// put the elements in a, b, c back in sorted order
for( std::size_t i = 0 ; i < temp.size() ; ++i )
{
c[i] = std::get<0>( temp[i] ) ;
a[i] = std::get<1>( temp[i] ) ;
b[i] = std::get<2>( temp[i] ) ;
}
}
std::cout << "\n---------- sorted ----------------\n\n" ;
print_vec(a) ;
print_vec(b) ;
print_vec(c) ;
}
| |