Saraph
Saraph

Reputation: 1002

Vector of structs inside of vector of structs

Imagine something like account database of social network in C++. Each account has it's username, level (admin, etc.), list of users who follow this account and list of users who messaged this account.

Problem is, I wanna count number of messages received by each separate user, so name and count in inner struct gotta be linked together.

Is this good idea of implementation?

    struct User {
        string name;
        int level;

        vector<string> followedBy;
        struct MessagedBy {
            string name;
            int count;
        };
    };

vector<User> users;
//@TODO vector of MessagedBy as an instance of User

How do I create vector of structs inside of vector of structs? How do I point at it?

Upvotes: 1

Views: 244

Answers (1)

Mats Petersson
Mats Petersson

Reputation: 129314

So, you would probably want something like this:

struct User {
        string name;
        int level;

    vector<string> followedBy;
    struct MessagedBy {
        string name;
        int count;
    };
    vector<MessageBy> messages;
};

You can then use:

cout << "Messages from: " << users[index].messages[otherindex].name << ":" << users[index].messages[otherindex].count;

Upvotes: 2

Related Questions