I am having trouble with wh开发者_开发问答at seems like a very simple concept. I have a class like such:
class Projectile
{
public:
int count;
int projectiles[1][3];
Projectile();
void newProjectile();
};
Projectile::Projectile()
{
count = 0;
}
void Projectile::newProjectile()
{
projectiles[0][0] = { 1, 2, 3 };
}
I am trying to set the values inside the projectiles
array, and I must be doing this incorrectly. How can I go about dynamically adding a set of values into this property?
projectiles[0][0]
refers to a specific location in a two-dimensional array, its type is int
If you want to dynamically add items, then you can use std::vector<int>
(see here)
projectiles[0][0] = { 1, 2, 3 };
This isn't correct. Initializer lists can only given at the point of declaration. You have to assign values independently to each location of the array elements. std::vector<std::vector> twoDimArray;
is what you want.
struct foo{
std::vector<std::vector<int> > twoDimArray;
void create(int size){
std::vector<int> oneDimArray(size);
// vector as of now can just accommodate size number of elements. They aren't
// assigned any values yet.
twoDimArray.push_back(oneDimArray); // Copy it to the twoDimArray
// Now if you wish to increase the size of each row, just push_back element to
// that row.
twoDimArray[0].push_back(8);
}
};
try this
void Projectile::newProjectile()
{
projectiles[0][0] = 1;
projectiles[0][1]=2;
projectiles[0][2]=3;
}
精彩评论