[英]priority_queue's emplace and push
我注意到一些代碼。 他們使用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,對嗎?
這沒有什么區別,因為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));
再一次,該結構非常簡單,以至於這一切都不會有任何不同。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.