如何在c++中清空/清除向量和数组

how do I empty/clear vector and array in c++

本文关键字:清除 向量 数组 清空 c++      更新时间:2023-10-16

假设我有一个类,

Class A {
  int x[100];
  vector<int> y;
  Fill(x);
  Fill(y.begin());
  B(x);
  B(y.begin());
}
Class Fill (pointer) {
  *pointer = 0;
  ++pointer;
  *pointer = 1;
  ++pointer 
}
Class B(container) {
  //how do I clear/empty the array and the vector passed by class A given only the pointers to them?
  //I must clear an array and a vector in THIS class.
  //I DO NOT want to fill them with 0s. 
  //x and y.begin are POINTERS to the first element of the container, not containers    
}

dsfsdakfgnsdfgsfdgsdfgsdfghsdfgsdfgersgs

提前谢谢。

对于矢量:

some_a_pointer->y.resize(0);

你不能只使用迭代器(y.begin())。

数组的大小永远不会改变,所以最好用0填充它。

std::vector有一个名为clear的方法,它将清除所有元素。

因此my_vector.clear();将清除所有内容。但是,您不能对数组执行同样的操作。这是不可能的。最多你可以用零来填充它们,或者走错误的路,动态分配数组,然后删除它。不过,我宁愿不处理内存问题,所以我只用零来填满它们。

C++11有一个名为std::array<T,N>的类,用于编译时大小的静态数组,它有一个称为fill的方法,可以轻松地将所有内容填充为零(la循环)。你可以用my_array.fill(0);来称呼它。