struct Event {
int start, finish;
};
struct Endpoint {
booloperator<(const Endpoint& e) const {
//if times are equal, times corresponding to start come first
return time != e.time ? time < e.time : (isStart && !e.isStart);
}
int time;
bool isStart;
};
int FindMaxSimultaneousEvents(const vector<Event>& A) {
//Builds an array of all endpoints
vector<Endpoint> E;
for(const Event& i : A) {
E.emplace_back(Endpoint{i.start, true});
E.emplace_back(Endpoint{i.finish, false});
}
//Sorts the endpoint array according to the time, breaking ties by printing start times before end times
sort(E.begin(), E.end());
//Track the number of simultaneous events, and record the maximum number of simultaneous events
int max_num_simultaneous_events = 0, num_simultaneous_events = 0;
for(const Endpoint& e: E) {
if(e.isStart) {
++num_simultaneous_events;
max_num_simultaneous_events = max(num_simultaneous_events, max_num_simultaneous_events);
} else {
--num_simultaneous_events;
}
}
return max_num_simultaneous_events;
}
By the way, I fully understand the workings of the code but I do have a question about a recurring C++ programming feature that has nagged me for a while. It concerns the statements in Lines 20 and 21: I expect the items being emplaced into vector E to be objects; not types. I do not see any declared objects being inserted/emplaced here; rather, I see the type Endpoint being used. Why?
It is objects (of types) that are initialized, not types! What is going on here?
If "there is an object being created right there" as you said, doesn't it violate the format/syntax for C++ object declaration statements shown below: Type object (initialization values);
It appears the format being used here is: Type (initialization values);
No object of type Endpoint was earlier declared locally in, or passed into, function FindMaxSimultaneousEvents; how is that acceptable?
You are correct that it does violate the syntax for object declaration statements, because it's not a statement (it's an expression), and I don't think you can call it a declaration either because the object does not have a name.
You should strive to substantiate your posts with instructive statements, clear explanations, and unimpeachable C++ concepts, not disconcerting phrases like "either don't use it or find a different programming language."
If you cannot defend your submissions in a forum like this where intelligent back-and-forth debate/discussion is encouraged, then kindly don't comment.