3

我有一个消息列表,每次添加消息时,我都会设置一个时间戳。我正在尝试创建一个函数,该函数将返回在一定时间内添加的消息,该消息也与字符串匹配。但是,我现在卡住了,非常感谢任何帮助,下面是我的代码:

struct BarMessage
{
    int Length;
    const char *message;
    time_t TimeAdded;
};

struct Ba
{
    vector<BarMessage> Messages;

    void AddMessage(const char *message, int Length)
    {
        BarMessage m;

        m.message = message;
        m.Length = Length;

        time(&m.TimeAdded); // set time ?

        Messages.push_back(m);
    }

    BarMessage & GetMessageWithin(string pattern, int span = 200)
    {
        //Time.Now?
        time_t now;
        time(&now);

        if (this->Messages.size() > 0)
        {
            for (auto & messages : this->Messages)
            {
                //Stuck here!!!

                //I want to return the BarMessage of a message
                //that was added within 200 (span)
                //that also contains the string patten inside it
            }
        }
    }
};
4

1 回答 1

1

首先在 BarMessage 中使用字符串

struct BarMessage
{
    int Length;
    string message;
    time_t TimeAdded;
};

有关查找匹配字符串的更多信息http://www.cplusplus.com/reference/string/string/find/char*您使用而不是有什么充分的理由string吗?您确定要从此函数返回引用吗?为什么将模式作为值而不是参考传递const

BarMessage & GetMessageWithin(const string& pattern, int span = 200)
{
    //Time.Now?
    time_t now;
    time(&now);

    if (this->Messages.size() > 0)
    {
        for (auto & messages : this->Messages)
        {
            if (now - messages.TimeAdded <= 200 && 
                messages.message.find(pattern) != std::string::npos) {
                //then return this message
            }
        }
    }
}
于 2012-12-25T18:40:37.143 回答