简体   繁体   中英

push_back a struct into a vector in a struct

I have the following structs:

enum messageType {New = 0, Old = 1, No_Message = 2};

typedef struct {
    enum messageType type;
    unsigned int senderID;
    char message[100];
} StoredMessageData;

struct StoredMessage {
    unsigned int recipientID;
    vector<StoredMessageData> messages;

    StoredMessage(const unsigned int& intRecipient = 0, const vector<StoredMessageData>& data = vector<StoredMessageData>())
    : recipientID(intRecipient), messages(data)
    {
        messages.reserve(10);
    }

    bool operator<(const StoredMessage& compareTo) const
    {
        return recipientID < compareTo.recipientID;
    }

    bool operator==(const StoredMessage& compareTo) const
    {
        return recipientID == compareTo.recipientID;
    }
};

In my main method, at some point I receive a message and want to store it like so:

if(msgs.find(rcvdRecipientID) == msgs.end())
{
    StoredMessage storedMsg;
    storedMsg.recipientID = rcvdRecipientID;
    msgs.insert(storedMsg);
}

set<StoredMessage>::iterator it = msgs.find(rcvdRecipientID);
StoredMessage storedMsg = *it;

StoredMessageData data;
data.type = New;
data.senderID = rcvdSenderID;
strcpy(data.message, rcvdMessage);

storedMsg.messages.push_back(data);

If, after push_back(), I call storedMsg.messages.size(), I am given a value of 1. This makes sense to me.

However, later, I wish to know how many messages I stored, so, this code:

StoredMessage storedMsg;
if(msgs.find(rcvdSenderID) != msgs.end())
{
    storedMsg = *(msgs.find(rcvdSenderID));
    cout << "Number of stored messages to send: " << int(storedMsg.messages.size()) << endl << endl;
    ...

Here, storedMsg.messages.size() returns 0 even when the same ID as before is used... I am confused as to why this is happening and suspect it has to do with the vectors being copied as their size varies, but I'm not sure. I am not a C++ expert, so please be gentle. Thank you!

Propbably it happens because here

StoredMessage storedMsg = *it;

You create the copy of object and do all the modifications to the copy.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM