user3709122
user3709122

Reputation: 15

put vectors into a map

My map: map <string, vector<vector<string> > >. The map key is the user name. vector<vector<string> > > is used to stored all messages an user received. vector<string> is used to store each message which has subject, data, etc.

Now I want to add vector<vector<string> > > into my map. My code :

vector<vector<string> > messageList;
vector<string> eachMessage;
    if(messageMap.find(name)==messageMap.end()) //to see if an user has already been put into the map
{
    messageMap.insert( pair<string, vector<vector<string> > >(name,messageList)); // create a new map

    eachMessage.push_back(subject); // add information
    eachMessage.push_back(totalMessage);
    messageList.push_back(eachMessage);// put each message into the messageList
}
else 
{
    eachMessage.push_back(subject);
    eachMessage.push_back(totalMessage);
    messageMap.find(name)->second.push_back(eachMessage);
}

However, this code can not correctly put message information for each user. Am I missing anything here?

Upvotes: 1

Views: 134

Answers (1)

Galik
Galik

Reputation: 48645

If you use the [] operator it will automatically create a new entry if it doesn't already exist meaning you don't need your big if(). You can reduce your code to this:

messageMap[name].push_back(vector<string>()); // new message
messageMap[name].back().push_back(subject); // add entries to the message
messageMap[name].back().push_back(totalMessage);

Remember messageMap[name] will create a new vector<vector<string> > if one doesn't already exist for that name or re-use the one that is already there.

The .emplace_back() adds a new vector<string> to the back of that vector.

The .back() access the vector<string> that you just made at the back.

Note: As @NeilKirk says in the comments you can be more efficient by taking a reference to the map element so it doesn't need to be looked up each time:

auto& messageList = messageMap[name]; // retrieve or create message list
messageList.push_back(vector<string>()); // new message
messageList.back().push_back(subject); // add entries to the message
messageList.back().push_back(totalMessage);

Upvotes: 1

Related Questions