priority_queue的安抚和推动

时间:2014-07-24 02:32:57

标签: c++ stl priority-queue

我在一些代码中注意到了。他们使用emplace代替'push',即使他们插入的元素实际上也是该实例。

例如。

class Star {
 public:
  // The distance between this star to the Earth.
  double distance() const { return sqrt(x_ * x_ + y_ * y_ + z_ * z_); }

  bool operator<(const Star& s) const { return distance() < s.distance(); }

  int ID_;
  double x_, y_, z_; 
};

vector<Star> find_closest_k_stars(int k, istringstream *sin) {
  // Use max_heap to find the closest k stars.
  priority_queue<Star> max_heap;
  string line;

  // Record the first k stars.
  while (getline(*sin, line)) {
    stringstream line_stream(line);
    string buf;
    getline(line_stream, buf, ',');
    int ID = stoi(buf);
    array<double, 3> data;  // stores x, y, and z.
    for (int i = 0; i < 3; ++i) {
      getline(line_stream, buf, ',');
      data[i] = stod(buf);
    }   
    Star s{ID, data[0], data[1], data[2]};

    if (max_heap.size() == k) {
      // Compare the top of heap with the incoming star.
      Star far_star = max_heap.top();
      if (s < far_star) {
        max_heap.pop();
        max_heap.emplace(s);
      }   
    } else {
      max_heap.emplace(s);  //I think here we  can use push instead of emplace, right?
    }   
  }
代码中的

:max_heap.emplace(s); //我想在这里我们可以使用push而不是emplace,对吧?

1 个答案:

答案 0 :(得分:3)

这没有区别,因为Star对象将以任何方式复制构造,代码应该做的是

max_heap.emplace(ID, data[0], data[1], data[2]); // Won't work without a Star ctor

max_heap.emplace(std::move(s));

max_heap.push(std::move(s));

然后结构很简单,很可能没有任何结果会产生任何影响。