I noticed in some code. They uses emplace
instead of ' push'
even the element they insert is actually that instance.
For example.
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?
}
}
in code :max_heap.emplace(s); //I think here we can use push instead of emplace, right?
It makes no difference here because the Star
object will be copy constructed either way, what the code should probably be doing is
max_heap.emplace(ID, data[0], data[1], data[2]); // Won't work without a Star ctor
or
max_heap.emplace(std::move(s));
or
max_heap.push(std::move(s));
Then again the struct is simple enough that it's likely none of this will make any difference whatsoever.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.