如何跟踪 C++ 对象 [英] How to keep track of C++ objects

查看:59
本文介绍了如何跟踪 C++ 对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有一个类场地,用于为构成我正在制作的游戏的场地的所有块制作对象.跟踪这个有点大的块列表的最佳方法是什么?我知道如何在 python 中跟踪对象,但我最近转向了 C++,我不确定如何设置某种易于迭代的列表.

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.

推荐答案

在 C++ 中,标准库(也称为标准模板库)提供了几个存储事物集合的容器类.事物"可以是任何数据类型,包括基本的和用户定义的.

In C++, the standard library (also referred to as the standard template library) provides several container classes that store a collection of things. 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.

最好的办法是使用 vector 如果您需要能够通过它们在容器中的位置来引用特定元素,或者使用 set 如果元素的顺序没关系,您需要能够快速检查某个元素是否存在.

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<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;

或者使用一组:

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.

这篇关于如何跟踪 C++ 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆