在列表C 中插入对象

Insert object in list c++

本文关键字:插入 对象 列表      更新时间:2023-10-16

我有这个类:

class UserLogRecord
{
public:
  std::string timestamp;
  std::string id; 
  std::string name; 
  std::string data; 
};

我正在迭代一个具有我的logdata的字符串向量,对于每个迭代,我都保存到我的列表中。

std::vector<std::string> lines = explode(filedata,'n');
std::list<UserLogRecord* > userLogRecords;
UserLogRecord* userLogRecord = new UserLogRecord;
//vector
for(int i = 0; i < lines.size(); i++)
{
  std::vector<std::string> elements = explode(lines[i], ';');
  userLogRecord->timestamp = elements.at(0);
  userLogRecord->id = elements.at(5);
  userLogRecord->name = elements.at(6);
  userLogRecord->data = elements.at(3);
  userLogRecords.push_back(userLogRecord);
}

Explode函数是解析FIFEDATA的辅助函数。我的FIFEDATA只有两个日志,因此for循环运行两次。之后,如果我遍及我的列表并显示时间戳和ID,它显示了2次,但相同的日志(最后一个具有相同时间戳,相同ID的日志(。

我是C 的新手,但是怎么了?我需要更改我的UserLogRecord以包括构造函数,并在循环中添加元素:

UserLogRecord* userLogRecord = new UserLogRecord(elements.at(0), elements.at(5), elements.at(6), elements.at(3));

然后使用push_backuserLogRecord添加到列表中?还是我的第一个实施应该起作用,但是我做错了什么?

您的第一个方法应该起作用;想一想,您可能需要发布预期/实际输出。如果您自己编码explode,也许很难进行调试,也许会发布该代码,并且可能是您问题的原因。