【问题标题】:Ordering a set of pairs in decending order by the first value and then alphabetically by the second value按第一个值降序排列一组对,然后按第二个值按字母顺序排列
【发布时间】:2017-07-18 03:19:52
【问题描述】:

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

【问题讨论】:

  • 您声明了itemsset,但引用了outputSet,而不是使用items。这是错误的吗?
  • 谢谢,我修正了错误
  • 你试过写比较函数吗?向我们展示您的尝试。

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


【解决方案1】:

一般来说,如果你想存储物品,并且有关于排序的特定规则,你会编写一个比较例程,这将确保排序是你想要的。

std::set 其中comparator有一个函数对象

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

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

【讨论】:

  • 只能使用return std::tie(rhs.first, lhs.second) &lt; std::tie(lhs.first, rhs.second)
猜你喜欢
  • 2016-11-07
  • 2021-05-03
  • 1970-01-01
  • 2016-07-19
  • 1970-01-01
  • 2012-02-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多