简体   繁体   English

push_back 一个结构体到一个结构体中的一个向量

[英]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.如果在 push_back() 之后,我调用了 storedMsg.messages.size(),我得到的值为 1。这对我来说很有意义。

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.在这里,即使使用与以前相同的 ID,storedMsg.messages.size() 也会返回 0 ......我很困惑为什么会发生这种情况,并怀疑这与被复制的向量有关,因为它们的大小不同,但我我不确定。 I am not a C++ expert, so please be gentle.我不是 C++ 专家,所以请保持温和。 Thank you!谢谢!

Propbably it happens because here可能是因为这里

StoredMessage storedMsg = *it;

You create the copy of object and do all the modifications to the copy.您创建对象的副本并对副本进行所有修改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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