I want to build an effective data structure for such a case:
There are lots of users, each user has an ID and a name. Each user can follow others. There are four kinds of commands that I need to handle: create-user, follow, delete-user and cancel-follow. Here is an example:
create-user id=3 name="Chandler"
create-user id=7 name="Janice"
create-user id=2 name="Joey"
follow id=3 id=7 # Chandler follows Janice
follow id=7 id=3 # Janice follows Chandler
follow id=2 id=7
follow id=7 id=2
delete-user id=7
follow id=3 id=2
follow id=2 id=3
cancel-follow id=3 id=2
In a word, I need to read a file, containing lots of commands as above and process all of the data.
Here is what I've tried (functions to handle the four kinds of commands):
struct User
{
unsigned long id;
string name;
unordered_set<User *> followers;
unordered_set<User *> fans;
User(unsigned long pid, const string & pname) : id(pid), name(pname) {}
};
list<User> users;
User & getUserById(list<User> & users, unsigned long id)
{
auto it = std::find_if(users.begin(), users.end(), [&](User & u) {return id == u.id;});
return *it;
}
void createUser(list<User> & users, unsigned long id, const string & str)
{
users.emplace_back(User(id, str));
}
void deleteUser(list<User> & users, unsigned long id)
{
auto itUser = std::find_if(users.begin(), users.end(), [&](User & u) {return id == u.id;});
auto itFans = itUser->fans;
for (auto it = itFans.begin(); it != itFans.end(); ++it)
{
(*it)->followers.erase(&*itUser);
}
auto itFollowers = itUser->followers;
for (auto it = itFollowers.begin(); it != itFollowers.end(); ++it)
{
(*it)->fans.erase(&*itUser);
}
users.erase(itUser);
}
void buildRelation(list<User> & users, unsigned long follower, unsigned long fan)
{
User & u1 = getUserById(users, follower); //3
User & u2 = getUserById(users, fan); //7
u1.fans.insert(&u2);
u2.followers.insert(&u1);
}
void cancelRelation(list<User> & users, unsigned long follower, unsigned long fan)
{
User & u1 = getUserById(users, follower); //3
User & u2 = getUserById(users, fan); //2
u1.fans.erase(&u2);
u2.followers.erase(&u1);
}
It works without any error.
However, I used my code to process a file, containing 70000-line commands, it took about 67 seconds.
I really want to get a better performance (20 seconds maybe?), I know I need a better data structure but for now I have no idea how to design a better one.