0

I am trying to sort a struct with an integer and a std::field. The primary sort 'field' should be the integer field (unsigned) but where integer field the same sort on string.

Using my sortfunc, see below, I get an assertion.

How do I fix this?

Debug Assertion Failed! file: agorithm line 3128 Expression operator<

problem line is if (_DEBUG_LT_PRED(_Pred, _Val, *_First)) in void _Insertion_sort1(_BidIt _First, _BidIt _Last, _Pr _Pred, _Ty *) in algorithm file.

Output using sortfunc_nocrash

unsorted list
1 Apples
1 Pears
4 Pineapples
1 Apricot
2 Mango
3 Banana
sorted list
4 Pineapples
3 Banana
2 Mango
1 Apples
1 Pears
1 Apricot

I need 1 Pears to be last printed item in sorted list above.

Here is the code:

#include <iostream>
#include <map>
#include <string>
#include <vector>
#include <algorithm>


struct names {
    unsigned n;
    std::string s;
};

bool sortfunc(names a, names b) {
    if(a.n > b.n) {
        return true;
    }
    else {
        return a.s.compare(b.s) < 0;  
    }
}

//This one works but I if n same want to sort on string
bool sortfunc_nocrash(names a, names b) {
    return a.n > b.n;
}

void sortlist(std::vector<names>& vec) {
 std::sort(vec.begin(), vec.end(), sortfunc_nocrash);
}

void printme(const names& mp) {
    std::cout << mp.n << " " << mp.s << std::endl;
}

int main() {

    names mp[] = { {1,"Apples"}, {1,"Pears"}, {4,"Pineapples"}, {1,"Apricot"}, {2,"Mango"}, {3,"Banana"}};
    size_t sz = sizeof(mp) / sizeof(mp[0]);
    std::vector<names> vec(mp, mp+sz);

    std::cout << "unsorted list\n";
    for_each(vec.begin(), vec.end(), printme);
    sortlist(vec);

    std::cout << "sorted list\n";
    for_each(vec.begin(), vec.end(), printme);

    return 0;
}

UPDATE:

Thanks for the feedback, this works ok now:

bool sortfunc(const names& a, const names& b) {
    return a.n == b.n ? a.s.compare(b.s) < 0 : a.n > b.n;
}

But I would really appreciate a link explaining rules for creating a sort predicate.

4

1 回答 1

1

像这样

bool sortfunc(names a, names b) {
    if (a.n > b.n) {
        return true;
    }
    else if (a.n == b.n) {
        return a.s.compare(b.s) < 0;  
    }
    else {
        return false;
    }
}

如果数字相等,您应该只比较字符串。您实际上在您的问题中这么说,但代码与您所说的不符。

于 2013-09-21T15:35:31.020 回答