We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
I think my approach is quite similar to the others already published here. It involves the usage of a static variable.
I added a static variable "order", class-wise.
In addition, each instance of Message also contains its own copy of order, called order_.
On creation time, Message() calls set_order() which increments the global order by one, then copies that value to the interval variable order_. For that, the Message's constructor calls set_order().
Messages are sorted by order_.
classMessage{public:Message(){// this will set the order or arrival, on creation timeset_order();}Message(conststringtext):Message(){text_=text;}conststring&get_text(){returntext_;}// global variable to keep count of the number of messages createdstaticintorder;// public getter functionintget_order()const{returnorder_;}// comparison operatorbooloperator<(constMessage&other)const{returnorder_<other.get_order();}private:stringtext_;// this is for internal useintorder_;// this is called on creation time: set the order of arrival for the messagevoidset_order(){order_=++Message::order;}};intMessage::order=0;classMessageFactory{public:MessageFactory(){}Messagecreate_message(conststring&text){returnMessage(text);}};
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Messages Order
You are viewing a single comment's thread. Return to all comments →
I think my approach is quite similar to the others already published here. It involves the usage of a static variable.
order
", class-wise.order_
.Message()
callsset_order()
which increments the globalorder
by one, then copies that value to the interval variableorder_
. For that, theMessage
's constructor callsset_order()
.order_
.