简体   繁体   English

如何跟踪C ++对象

[英]How to keep track of C++ objects

I currently have an class grounds which is used to make objects for all the blocks that make up the ground for a game I am making. 我目前有一个课堂背景,用于为构成我正在制作的游戏的地面的所有块制作对象。 What is the best way to keep track of this somewhat large list of blocks? 跟踪此较大的块列表的最佳方法是什么? I know how to keep track of objects in python but I recently moved to C++ and I am unsure of how to go about setting up some sort of list that is easy to iterate through. 我知道如何跟踪python中的对象,但是最近我移到了C ++,我不确定如何建立易于迭代的某种列表。

In C++, the standard library (also referred to as the standard template library) provides several container classes that store a collection of things. 在C ++中,标准库(也称为标准模板库)提供了几个存储事物集合的容器类 The "things" may be any data type, including fundamental and user-defined. “事物”可以是任何数据类型,包括基本数据和用户定义的数据类型。

Which container to use depends on your needs. 使用哪个容器取决于您的需求。 Here's an authoritative article on it from Microsoft . 这是Microsoft的权威文章

Your best bet is to use either vector if you need the ability to refer to specific elements by their position in your container, or a set if the order of elements doesn't matter and you need to quickly be able to check whether a certain element is present. 最好的选择是,如果需要根据容器中的位置引用特定元素的能力,则使用vector ;或者如果元素的顺序无关紧要,则使用set ,并且需要快速检查是否有某个元素存在。

Some examples: 一些例子:

vector<MyClass> mycontainer; // a vector that holds objects of type MyClass
MyClass myObj;
mycontainer.push_back(myObj);
cout << mycontainer[0] << endl; // equivalent to cout << myObj << endl;

Or using a set: 或使用一套:

set<MyClass> mycontainer;
MyClass myObj;
mycontainer.insert(myObj);
if (mycontainer.find(myObj))
   cout << "Yep, myObj is in the set." << endl;

The reason there's no one ultimate container is that there are efficiency tradeoffs. 没有一个最终的容器的原因是效率之间的权衡。 One container may be blazing-fast at identifying whether an element is present within it, while another is optimal for removing an arbitrary element, etc. 一个容器在识别其中是否存在某种元素时可能会非常快,而另一种容器对于删除任意元素是最佳选择,等等。

So your best bet is to consider what behaviors you want your container to support (and how efficiently!), and then to review the authoritative article I linked to earlier. 因此,最好的选择是考虑希望容器支持哪些行为(以及效率如何!),然后查看我之前链接的权威文章。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM