【问题标题】:how do I empty/clear vector and array in c++如何在 C++ 中清空/清除向量和数组
【发布时间】:2013-07-14 02:20:05
【问题描述】:

假设我有一门课,A

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    
}

dsfsdakfgnsdfgsf dg 自卫队 全球自卫队 ghsdf G sdfg ersg s

提前谢谢你。

【问题讨论】:

  • 清空数组是什么意思?
  • 如果数组有 [1,2,3,4] 那么我想把它设为 []。
  • 嗯.. 语法对于初学者来说并不真正有效。考虑解决这个问题。
  • 你不能那样做。数组声明后无法调整大小。
  • 类不是函数。

标签: c++ arrays pointers vector iterator


【解决方案1】:

对于矢量:

some_a_pointer->y.resize(0);

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

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

【讨论】:

    【解决方案2】:

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

    所以my_vector.clear(); 将清除所有内容。但是你不能对数组做同样的事情。这是不可能的。充其量你可以用零填充它们或走错路并动态分配数组然后删除它。我宁愿不处理内存问题,所以我只是用零填充它们。

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

    【讨论】:

    • 问题出在B类中,我只有指向数组和向量的指针。我显然不能在指针上调用“清除”。
    • @Nayana 你想做的事是不可能的。
    • @Nayana 认为您的方法是糟糕的设计。最好将分配/解除分配作为所有者类责任,您应该在class A中实现这些功能
    • @Nayana:你有指向向量的指针,还是只有指向其元素的指针/迭代器?
    • @BenVoigt 他之前提到它只是一个迭代器。
    猜你喜欢
    • 2021-02-03
    • 2010-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-30
    • 1970-01-01
    • 2018-11-03
    • 1970-01-01
    相关资源
    最近更新 更多