我正在制作一个关于弹珠的游戏,它使用一个结构来描述弹珠的属性:
struct Marble
{
Color color;
int weight;
//Other customizable marble properties
};
我目前正在使用 std::vector
来跟踪哪些弹珠在游戏板上的哪个位置:
std::vector<Marble> m_marbles;
在任何时候,我都可以通过索引 vector 来检查给定弹珠位置的属性。查看位置 20 的弹珠颜色:
m_marbles[20].color;
用户可以创建自定义弹珠并将它们添加到游戏板上。如果我想在游戏板上添加一个新的弹珠,我创建一个新的结构对象并将其推送到 vector 上:
Marble m;
//Fill struct with marble information
m_marbles.push_back(m)
问题是游戏板非常大(有数千颗弹珠),而且许多弹珠完全相同。
假设游戏板上有 4000 个位置。其中可能有 3000 个是权重为 1.0 的红色弹珠。在当前的解决方案中,3000 个等效的 Marble 对象占用了我的 vector 中的空间。
由于用户可以定义自己的弹珠类型,我不能只对所有可能的弹珠类型进行硬编码,然后让 vector 存储指向适当弹珠对象的指针。
我正在考虑使用 std::set
来存储不同的大理石类型。然后,当用户开始创建他的自定义弹珠时,他可以尝试将其插入到集合中。如果已经存在相同类型的弹珠,则不会浪费内存。
我的问题是,如何将引用存储到 std::set
中?例如,假设我的集合包含这些弹珠类型:
{RedMarble, BlueMarble, StrangeMarble, ConfusedMarble}
现在我想在游戏板上的第 20 个位置分配一个红色弹珠:
m_marbles[20] = ?
我还想检查位置 31 的大理石颜色:
m_marble[31].color;
是否有可能以这种方式处理集合?查找和插入函数返回迭代器,但如果我向集合中插入更多项,这些迭代器不会失效吗?
最佳答案
是的,你可以做你想做的事。您可以在 vector 中存储指针,这些指针指向集合中的 Marbles。或者您可以将迭代器存储在您的 vector 中,迭代器再次指向您集合中的 Marbles。
下面是我将如何使用指针来实现:
// A useful helper funtction -- not required, but useful.
const Marble* Helper(const Marble& m) {
static std::set<Marble> uniqueMarbles;
return &*(uniqueMarbles.insert(m).first);
}
// A vector of pointers to marbles
std::vector<const Marble*> m_marbles;
// You can pass temporaries to the helper function, and it returns a permanent pointer
m_marbles.push_back(Helper(Marble(RED, 1.0));
Marble m;
m.setColor(BLUE);
m_marbles.push_back(Helper(m));
// You can reference your marbles
Color c = m_marbles[i]->getColor();
// Hopefully the following will produce a compiler error message
m_marbles[i]->setColor(GREEN); // Oops, m_marbles holds const pointers
关于c++ - 存储对 std::set 对象的引用/指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13483096/