【问题标题】:How to sort pointer in stl set? [duplicate]如何对stl set中的指针进行排序? [复制]
【发布时间】:2021-05-22 12:16:53
【问题描述】:

在c++中,set可以自动对值进行排序,所以我只需要插入就行了。

对于自定义结构,我只需要定义运算符>和

#include <iostream>
#include <cmath>
#include <set>

using namespace std;

struct A { 
  A(int a) : a_(a) {}
  friend bool operator <(const A& shot1, const A& shot2) {
    return shot1.a_ < shot2.a_;
  }
  friend bool operator >(const A& shot1, const A& shot2) {
    return shot1.a_ > shot2.a_;
  }
  int a_; 
};

int main(int argc, char** argv) {
  std::set<A> s;
  A a1(10), a2(11), a3(9);
  s.insert(a1);
  s.insert(a2);
  s.insert(a3);
  for (auto i : s) {
    cout << i.a_ << endl;  // 9, 10, 11, it's sorted.
  }
}

这可以工作,但是当我有一个自定义结构时,它很重,所以复制构造函数会很昂贵。我想像这样设置保存指针:

#include <iostream>
#include <cmath>
#include <set>

using namespace std;

struct A {   // NOTICE HERE: A's contructor is very heavy
  A(int a) : a_(a) {}
  friend bool operator <(const A& shot1, const A& shot2) {
    return shot1.a_ < shot2.a_;
  }
  friend bool operator >(const A& shot1, const A& shot2) {
    return shot1.a_ > shot2.a_;
  }
  int a_; 
};

int main(int argc, char** argv) {
  std::set<A*> s;
  A a1(10), a2(11), a3(9);
  s.insert(&a1);
  s.insert(&a2);
  s.insert(&a3);
  for (auto i : s) {
    cout << i->a_ << endl;  // 10, 11, 9, not sorted!!!!!!!
  }
}

但是我认为设置排序功能失败了,那么,当设置值是指针时,我怎样才能让它工作呢?

【问题讨论】:

    标签: c++ stl


    【解决方案1】:

    集合不再是对象A,而是指针:A*。因此,集合的默认排序是在指针到整数的转换上执行的,它是在内存中对其位置进行排序。为避免这种情况,需要一个自定义比较运算符,它会绕过所需的实例排序。

    您可以定义自己的比较函数,如下例所示。

    这个想法是创建一个仿函数:一个具有运算符括号的结构,并在所需对象之间实现比较(小于):

    bool operator()(Obj a, Obj b); //Less comparison.
    

    那么,类就可以用在集合的模板中了:

    #include <iostream>
    #include <cmath>
    #include <set>
    
    using namespace std;
    
    struct A {   // NOTICE HERE: A's contructor is very heavy
      A(int a) : a_(a) {}
      friend bool operator <(const A& shot1, const A& shot2) {
        return shot1.a_ < shot2.a_;
      }
      friend bool operator >(const A& shot1, const A& shot2) {
        return shot1.a_ > shot2.a_;
      }
      int a_; 
    };
    
    struct Comp
    {
        bool operator()(const A* a, const A* b)
        {
            if (a && b)
            {
                return *a < *b;
            }
            return a<b;
        }
    };
    
    int main(int argc, char** argv) {
      std::set<A*, Comp> s;
      A a1(10), a2(11), a3(9);
      s.insert(&a1);
      s.insert(&a2);
      s.insert(&a3);
      for (auto i : s) {
        cout << i->a_ << endl;  // 10, 11, 9, not sorted!!!!!!!
      }
    }
    

    有关如何为集合创建自定义比较器的更多信息:

    Using custom std::set comparator

    【讨论】:

      猜你喜欢
      • 2020-09-11
      • 1970-01-01
      • 2019-04-16
      • 1970-01-01
      • 2021-04-06
      • 1970-01-01
      • 2011-02-15
      • 2011-02-03
      相关资源
      最近更新 更多