使用c++后,将堆栈恢复到以前的状态

Getting a stack back to previous state after using it c++

本文关键字:状态 恢复 堆栈 c++ 使用      更新时间:2023-10-16

堆栈可能不适合我的需求和其他东西,所以如果需要更好的数据结构,请教育我。

我正在尝试检索从最近创建到最旧的Record对象。我决定,应该将这些Record对象推入堆栈中,以便于检索。我的程序中的每个Person对象都有一个堆栈(可以很容易地将每个Person的记录分开(,每个Person都有一堆记录。如果我想要n个最近制作的记录,我可以只top()pop()这n个记录,由于堆栈的原因,它们已经按顺序排列了。

然而,我刚刚意识到我正在更改堆栈内容,因此丢失了所有弹出的记录。

有没有更好的方法来实现我的目标,即将记录整理好,以便保存容器?请告诉我。非常感谢。

void Person::printAllRecords() {
while (this->log.size() >= 1) 
{
std::string recordType = this->log.top()->checkRecordType(); 
std::cout << recordType << " made on: "; 
this->log.top()->displayDateCreated(); 
this->log.pop(); 
}
}

您可以使用std::vector在不更改记录中的数据的情况下迭代记录。您可以在cplusplus.com上了解std::vector

用您自己的类初始化矢量:

std::vector<CustomClass> log;
for(int i=0; i < numberOfItems; i++){
CustomClass customClass; 
//Create object of your class and Initialse it with values.
log.push_back(customClass);
}

现在迭代您的矢量:

void Person::printAllRecords() {
for( int i = this->log.size()-1; i>=0; i--)
{
std::string recordType = this->log.at(i).checkRecordType(); 
std::cout << recordType << " made on: "; 
this->log.at(i).displayDateCreated();
}
}