c++ - How to make a dynamic storage of objects (c++)
问题描述
I am a beginner to programming and I am trying to find a way to create a dynamic storage of objects of my pigeon class. Here is my code:
class pigeon {
public:
pigeon(std::string nameI);
void outputInfo();
private:
std::string name;
};
The idea is that I want to be able to add a new object, have a place to store its information, then be able to add another object, and so on. I have no idea where to start with this or even what data structure to use, I have no experience storing objects.
解决方案
正如评论中已经指出的那样,您最好使用按照RAII/RDID-idiom(“资源获取是初始化”/“资源破坏是删除”)处理其资源的容器,这样您就不必担心关于它自己。这也是在抛出异常时防止资源泄漏的一种简单方法。
C++ 标准库的常用容器之一是std::vector<>
.
你会像这样使用它(只是为了给你一个初步的想法,请参阅文档以获得进一步的解释和示例):
#include <vector>
// ...
{
std::vector<pigeon> pigeons;
pigeons.push_back("Karl"); // add three pigeons
pigeons.push_back("Franz"); // at the end of the
pigeons.push_back("Xaver"); // vector
pigeons[1]; // access "Franz"
for(auto /* maybe const */ &p : pigeons) { // iterate over the vector
// do something with pigeon p
}
} // pigeons goes out of scope, its destructor is called which
// takes care of deallocating the memory used by the vector.
推荐阅读
- javascript - JavaScript 函数和事件
- python-3.x - 用 python Beautifulsoup 抓取
- java - 错误:Model::findById 需要参数 id loopback android
- javascript - 编辑最小化 javascript 的源代码
- c# - 将 ulong 从 c++ 转移到 c#
- python - 为什么python不返回None?
- php - Wordpress 插件 - 需要添加 PHP 功能
- php - 参数无效的 Pdo 错误
- rest - 如何在 Rest API 中维护静态引用数据
- bash - 用于检查乘法结果并引发错误的 AWk 脚本