Delete Zero in ArrayList in C++



在ArrayList中,我试图删除作为输入附加的所有可能的0,但现在它只删除一个0,无论它位于何处。但似乎我不能同时删除一个以上的零。我该如何解决这个问题?

void AList::elimZeros(){
int i;
int curr = 0;
for(i=0; i < listSize; i++) {
if ( (listArray[i] != 0 ) && (curr<listSize) ){
listArray[curr] = listArray[i];
curr++;
}
else if (listArray[i] == 0 )
{
listArray[curr] = listArray[i+1];
listSize--;
curr++;
}
}
}

这是ADT的类

class AList : public List {
private:
ListItemType* listArray;            // Array holding list elements
static const int DEFAULT_SIZE = 10; // Default size
int maxSize;                        // Maximum size of list
int listSize;                       // Current # of list items
int curr;                           // Position of current element
// Duplicates the size of the array pointed to by listArray
// and update the value of maxSize.
void resize();
public:
// Constructors
// Create a new list object with maximum size "size"
AList(int size = DEFAULT_SIZE) : listSize(0), curr(0) {
maxSize = size;
listArray = new ListItemType[size];         // Create listArray
}
~AList();     // destructor to remove array

这是我要测试的输入:

int main() {
AList L(10);
AList L2(20);
L.append(10);
expect(L.to_string()=="<|10>");
L.append(20);
expect(L.to_string()=="<|10,20>");
L.append(30);
L.append(0);
L.append(40);
L.append(0);
L.append(0);
expect(L.to_string()=="<|10,20,30,0,40>");
L.elimZeros();
expect(L.to_string()=="<|10,20,30,40>");
assertionReport();
}

如果您发布了list的类代码将会很有帮助。认为你混淆了Java的数组列表类型,但假设你使用向量,你总是可以这样做:

for (int i = 0; i < listSize; i++) {
if(listArray[i] == 0) listArray.erase(i);
}

编辑:假设这是list类的模板,那么只有一个remove()函数。关于你的代码,有两个问题。

在for循环中引用listSize,然后在循环中递减它。每次迭代分别求值,这样就减少了循环迭代的总次数,并提前停止。

另一件事是,如果条目是零,你不应该增加curr和设置listArray[curr] = listArray[i+1]。这基本上是假设下一项不是零。如果是,那么你就复制这个元素,然后移动到下一个元素。你的if语句可以用:

if (listArray[i] == 0) {
listSize--;
} else {
listArray[curr] = listArray[i];
curr++;
}

最新更新