- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我有一个类unit
,有一个元素int holding[4];
void main()
{
vector<vector<unit> > allunits;
vector<vector<short> > selectedunits; //This contains certain indexes for the above vector
allunits.resize(2);
selectedunits.resize(2);
allunits[0].resize(5);
int *ptr = &allunits[0][selectedunits[0][0]].holding[0]; //obviously dysfunctional
}
我想要的是让这个指针动态地改变它指向的东西。当selectedunits[0][0]
的值改变时,我希望ptr
自动指向allunits[0][selectedunits[0]的新值[0]].持有[0]
。当 selectedunits[0]
是一个空 vector 时,ptr
可以是任何东西,但它不能抛出运行时错误,这就是它现在所做的。
所以,如果我以后有代码 selectedunits[0].push_back(2);
,我希望 ptr
指向 allunits[0][ 2].holding[0]
,然后行 selectedunits[0][0]=1;
应该使 ptr
指向 allunits [0][1].持有[0]
编辑:这段代码的要点:
这一切都是为了一个游戏。 allunits
是单位 vector ,selectedunits
存储选择了哪些单位。它们是二维的,因为它们都被组织成 [player][index]。 allunits[0]
保存第一个玩家的单位,依此类推。
指针被传递给一个对象的构造函数,该对象在特定条件下将文本打印到屏幕上。要打印的文本是有关所选单元的信息,包括指针指向的任何数字。不同的对象会打印不同的数据,因此会打印不同的数据。
最佳答案
使用函数或类。如果您使用的是 C++11,请在本地创建一个绑定(bind)到 vector 的 lambda。否则,创建一个将 vector 作为常量引用参数的函数,或者将 vector 移动到它们自己的类中并将访问器代码放入成员函数中。
关于c++ - 如何在 C++ 中创建一个 'dynamic' 指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14024808/
我是一名优秀的程序员,十分优秀!