简体   繁体   中英

How to clear Vector in C++?(not std::vector)

I have a Vector stuct like this:

struct Vector {
   float x, y, z;

   Vector( ) {
    x = y = z = 0;
   }
   Vector(float x0, float y0, float z0 = 0) {
    x = x0; y = y0; z = z0;
   }
}

I make a new instant of vector-> Vector v [5]; I filled up this array with numbers, but I want to clear this.

I tried this: v = Vector(); but it doesn't work. (I want to call the default constructor of the Vector, which will clear my array?)

Or the only solution is that go through with a for loop and clear one by one?

You don't need a for loop:

Vector v[5];
// ...
std::fill(std::begin(v), std::end(v), Vector()); // clears v.

If you write :

Vector v [5];

The program just allocates 5 contiguous Vector objects in memory. You can switch from one to another using [] operator but 'v' is not an array object.

If you want to reset all data to 0, like in your constructor you have to go through all elements by hand :

for (int i = 0; i < 5; ++i)
  v[i] = Vector();

Or better:

for (int i = 0; i < 5; ++i)
  v[i].reset();

Where reset() would be a member of Vector which is in charge of setting values to 0, like the constructor (it is more efficient since it does not construct a new object).

You may prefer using std::vector if you have an array of various size. You would also be able to use std::fill() and other algorithms.

std::vector<Vector> v;
v.resize(5);
std::fill(std::begin(v), std::end(v), Vector()); // clears v

Vector v[5]; does not declare a new instance of vector, it declares an array of five vectors. You can't assign a single vector to an array of vectors.

You can loop through the array and assign a default-constructed object to each element:

for (Vector& i : v)
  i = Vector();

If you're not using C++11 you can do it the old-fashioned way:

for (int i = 0; i < 5; ++i)
  v[i] = Vector();

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