使用c++后,将堆栈恢复到以前的状态
Getting a stack back to previous state after using it c++
堆栈可能不适合我的需求和其他东西,所以如果需要更好的数据结构,请教育我。
我正在尝试检索从最近创建到最旧的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();
}
}
相关文章:
- 用C++将哈希表写入文件并从文件中恢复
- Constexpr替代了新的放置方式,可以让内存中的对象保持未初始化状态
- 我不断收到 [错误] ID 返回 1 退出状态错误,但看不到问题所在
- OSX MetalKit CVMetalTextureCacheCreateTextureFromImage失败,状态:
- std::future_error:无关联状态
- 如何避免LED在循环状态变化中闪烁?
- 使用c++后,将堆栈恢复到以前的状态
- 无法恢复我的安卓 c++ 游戏的状态(状态>保存状态始终为空)
- 如何在C++中保存和恢复 TensorFlow 图及其状态
- 如何使用CUDA CURAND保存和恢复随机数生成器的状态
- 正在恢复 OpenGL 状态
- 在基于对话框的MFC应用程序中保存和恢复元素的状态
- 如何使系统进入睡眠状态并再次自动(以编程方式)从睡眠状态恢复,而无需任何手动"鼠标单击或键盘点击"
- 支持存储/恢复排序状态的PRNG库
- 如何保存std::mersenne_twister_engine的状态以便以后恢复
- C++RAII来管理对象状态的更改和恢复
- 如何保存-恢复所有opengl状态变量
- 如何恢复绘图后的QPainter状态
- 协程或有状态/可恢复任务与chiscript
- 如何强制DirectX恢复之前的渲染状态?