按第一个值的递减顺序对一组对进行排序,然后按第二个值的字母顺序排序

Ordering a set of pairs in decending order by the first value and then alphabetically by the second value

本文关键字:排序 顺序 然后 第二个 第一个 一组      更新时间:2023-10-16

我有一组整数和集合对,例如: items = {(2,{"A", "B", "C"}(,(3,{"C"}(,...}
我之所以这样设置它,是因为可以通过为声明编写比较器来轻松排序 stl 集,我不知道如何编写这样的函数来做我需要的事情。我需要根据整数值(该对的第一个值(按降序打印出来,如果两个项目共享一个整数值,则按字符串的字母顺序打印出来。目前,它按整数值升序打印出来,按字符串字母顺序打印出来。我将在下面附上预期和当前输出。

set<pair<int, set<string>>> outputSet;
map<set<string>, int> supportMap;
set<set<string>> candidateItemSets;
vector<set<set<string>>> frequentItemSets;
for(int i = 0; i < frequentItemSets.size(); i++){
for(auto it = frequentItemSets[i].begin(); it != frequentItemSets[i].end(); it++){
pair<int, set<string>> temp(supportMap[*it],*it);
outputSet.insert(temp);
}
}
for(auto it = outputSet.begin(); it != outputSet.end(); it++){
pair<int, set<string>> temp = *it;
auto sit = temp.second.begin();
auto end = temp.second.end();
advance(end, -1);
cout << temp.first << " [";
for(sit; sit != end; sit++)
cout << *sit << " ";
cout << *sit << "]" << endl;
/**
current output:  
2 [A]  
2 [A C]  
2 [B]  
2 [B C]  
2 [B C D]  
2 [B D]  
2 [C D]  
2 [D]  
3 [C]  
expected output:  
3 [C]  
2 [A]  
2 [A C]  
2 [B]  
2 [B C]  
2 [B C D]  
2 [B D]  
2 [C D]  
2 [D]
**/

通常,如果要存储项目,并且具有有关排序的特定规则,则应编写一个比较例程,以确保排序是您想要的。

std::set<类型、比较器>其中比较器具有函数对象

下面的比较器将反转数字测试,因此排序是你最初想要的。

bool operator()(const std::pair< std::string, int> &lhs, const std::pair<std::string, int> &rhs) const 
{
if( lhs.first < rhs.first ) // string ordering is already correct
return true;
if( lhs.first > rhs.first ) 
return false;  // needed to ensure we don't test second.
if( lhs.second > rhs.second )
return true;
return false;
}