首页 > 解决方案 > 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.

标签: c++data-structures

解决方案


正如评论中已经指出的那样,您最好使用按照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.

推荐阅读