简体   繁体   中英

How do I create a 'dynamic' pointer in c++

I have a class unit , with an element 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
}

What I would like is to have this pointer change what it points to dynamically. When the value of selectedunits[0][0] changes, I want ptr to automatically point to the new value of allunits[0][selectedunits[0][0]].holding[0] . When selectedunits[0] is an empty vector, ptr can be anything, but it can't throw a runtime error, which is what it does now.

So, if I later have the code selectedunits[0].push_back(2); , I want ptr to point to allunits[0][2].holding[0] , and then the line selectedunits[0][0]=1; ought to make ptr point to allunits[0][1].holding[0]

Edit: The point of this code:
This is all for a game. allunits is a vector of units, and selectedunits stores which units are selected. They are two dimensional since they are both organized into [player][index]. allunits[0] holds the units of the first player, and so on.

The pointer is passed to a constructor for an object that prints text to the screen, under certain conditions. The text to be printed is information about the selected unit, and includes whatever number the pointer is pointing to. A different object would print different data, hence the pointer.

Use a function or class. If you're in C++11, create a lambda locally that binds to the vectors. Otherwise, create a function that takes the vectors as const by-reference arguments, or move the vectors into their own class and put the accessor code in a member function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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