#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Message {
private:
string text;
public:
Message() {}
explicit Message(const string& text) : text(text) {}
const string& get_text() const {
return text;
}
bool operator<(const Message& other) const {
return false; // Messages are not compared
}
};
class MessageFactory {
public:
MessageFactory() {}
Message create_message(const string& text) {
return Message(text);
}
};
class Network {
public:
static void send_messages(vector messages, Recipient& recipient) {
// Simulate network delay
random_shuffle(messages.begin(), messages.end());
for (const auto& message : messages) {
recipient.receive(message);
}
}
};
class Recipient {
private:
vector messages;
public:
Recipient() {}
void receive(const Message& message) {
messages.push_back(message);
}
void print_messages() {
fix_order();
for (const auto& message : messages) {
cout << message.get_text() << endl;
}
messages.clear();
}
void fix_order() {
sort(messages.begin(), messages.end());
}
};
int main() {
MessageFactory message_factory;
Recipient recipient;
int n;
cin >> n;
cin.ignore(numeric_limits::max(), '\n');
vector messages;
for (int i = 0; i < n; ++i) {
string text;
getline(cin, text);
messages.push_back(message_factory.create_message(text));
}
Network::send_messages(messages, recipient);
recipient.print_messages();
return 0;
}
Code Explanation
The Message class stores the text value of a message and provides a getter method get_text() to retrieve the text value. It also implements the < operator, although in this case it always returns false since we don't compare messages.
The MessageFactory class has an empty constructor and a method create_message() that creates a new Message object with the given text.
The Network class simulates sending messages over a network. It shuffles the messages randomly and passes them to the recipient using the recipient.receive() method.
The Recipient class stores the received messages in a vector. It provides methods to receive a message, print the messages in the correct order, and fix the order of the messages using std::sort().
In the main() function, we create an instance of MessageFactory and Recipient. We read the number of messages from input and create the Message objects using the MessageFactory. We then call Network::send_messages() to simulate sending the messages to the recipient. Finally, we call recipient.print_messages() to print the received messages in the correct order.
Input:
4
Alex
Hello Monique!
What's up?
Not much :(
Output:
Alex
Hello Monique!
What's up?
Not much :(