按第一个值按降序排列一组对,然后按字母顺序按第二个值排序

时间:2017-07-18 03:19:53

标签: c++ stl comparator std-pair stdset

我有一组整数和集合,例如: 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]
**/

1 个答案:

答案 0 :(得分:0)

一般来说,如果你想存储物品,并且有关于订购的具体规则,你会写一个比较例程,这将确保订购符合你的要求。

的std ::设置&LT;类型,比较器&gt;比较器有一个功能对象

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

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;
}