整数と std::field で構造体をソートしようとしています。プライマリ ソート「フィールド」は整数フィールド (符号なし) である必要がありますが、整数フィールドは文字列で同じソートになります。
私のsortfuncを使用して、以下を参照してください。私はアサーションを取得します。
これを修正するにはどうすればよいですか?
デバッグ アサーションに失敗しました! ファイル: アルゴリズム行 3128 式演算子 <
問題の行は、アルゴリズム ファイルの void _Insertion_sort1(_BidIt _First, _BidIt _Last, _Pr _Pred, _Ty *) の if (_DEBUG_LT_PRED(_Pred, _Val, *_First)) です。
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
上記の並べ替えられたリストで最後に印刷されたアイテムになるには、梨が1つ必要です。
コードは次のとおりです。
#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;
}
アップデート:
フィードバックをお寄せいただきありがとうございます。これで問題なく動作します:
bool sortfunc(const names& a, const names& b) {
return a.n == b.n ? a.s.compare(b.s) < 0 : a.n > b.n;
}
しかし、ソート述語を作成するためのルールを説明するリンクを本当に感謝します。