Dynamic Sorting Predicate

Pages: 12
> can I access elements beyond the two provided as arguments to the predicate?

You can, by doing a tag sort on pointers. But the very idea of
Thus, starting from an element, I need to find a position, which is then used to access a nearby element.
doesn't make sense in the middle of a sort - the positions keep changing over and over again as the sequence is being sorted.

What you can do is pre-compute weights based on nearby elements in the original sequence and then sort based on those weights. For example with the weight of seq[i] being seq[i-1] + seq[i+1] (with zeroes for non-existing elements):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <vector>
#include <utility>
#include <algorithm>
#include <iostream>

int main()
{
    std::vector<int> seq = { 67, 47, 50, 69, 70, 79, 85, 74, 63, 52, 49, 58 } ;
    for( int v : seq ) std::cout << v << ' ' ;
    std::cout << '\n' ;

    std::vector< std::pair<int,int> > temp ; // weight for sorting, element
    temp.emplace_back( seq[1], seq[0] ) ;
    for( std::size_t i = 1 ; i < (seq.size()-1) ; ++i )
        temp.emplace_back( seq[i-1] + seq[i+1], seq[i] ) ;
    temp.emplace_back( seq[ seq.size() - 2 ], seq.back() ) ;

    std::sort( temp.begin(), temp.end() ) ; // sort on weights
    for( std::size_t i = 0 ; i < seq.size() ; ++i ) seq[i] = temp[i].second ;

    for( int v : seq ) std::cout << v << ' ' ;
    std::cout << '\n' ;
}

Last edited on
I've only looked over this thread briefly but if you are determined to use a predicate and you need those extra values, you might want to try looking into bind1st or bind2nd to bind the values you want to the predicate or just store the parts of the vector you want in a function object class, overload the () operator and within the f.o. class you will have access to the data you need
Topic archived. No new replies allowed.
Pages: 12