卡住,需要帮助从矢量列表返回时间跨度

时间:2012-12-25 18:32:08

标签: c++

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

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
            }
        }
    }
};

1 个答案:

答案 0 :(得分: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
            }
        }
    }
}