0

我有一个系统可以自动读取存储在他公司员工访问卡上的信息。这些信息存储在一个数组中。当读卡器不工作时,员工必须在读卡器附近的密码键盘上输入他的姓名和密码才能进入大楼,读卡器会自动创建信息并存储在阵列中。数组的第三个第一个单元格总是用正确的值填充,其余的单元格用 0 填充。我的工作是访问这个数组并删除第三个元素之后所有不相关的零,即使它之前存在 0第三个要素,这个必须保留。

我有以下代码:

    #include <iostream>  
    #include <string>      
    using namespace std;  
    int main(){  
      int const Taille=5;  
      int Track2[Taille], i;      
      Track2[0]=1;  
      Track2[1]=0;  
      Track2[2]=3;  
      Track2[3]=0;  
      Track2[4]=0;      
      cout<<"voici le contenu du tableau: \n";  
      for(i=0;i<Taille;i++){  
        if(Track2[i]!=0){  
        cout<<"Track2["<<i<<"]= "<<Track2[i]<<"\n";  
    }  
     }  
    return 0;  
    }  

执行此操作时,我得到以下结果: voici le contenu du tableau: Track2[0]= 1 Track2[2]= 3我想得到这个结果:voici le contenu du tableau: Track2[0]= 1 Track2[ 1]= 0 Track2[2]= 3这意味着,只有在我的数组的第 tird 元素(此处为 Track2[2])之后 = 0 的值必须从我的数组中删除。请问我该怎么做?谢谢

4

4 回答 4

3

如果您使用 C++,请使用std::vector 。std::vectorerase方法,用它。

#include <iostream>
#include <vector>




int main ()
{
  std::vector<int> myvector;

  // set some values (from 1 to 10)
  for (int i=1; i<=10; i++) myvector.push_back(i);

  // erase the 6th element
  myvector.erase (myvector.begin()+5);

  // erase the first 3 elements:
  myvector.erase (myvector.begin(),myvector.begin()+3);

  std::cout << "myvector contains:";
  for (unsigned i=0; i<myvector.size(); ++i)
    std::cout << ' ' << myvector[i];
  std::cout << '\n';

  return 0;
}

sts::vector::erase文档。

于 2012-12-05T10:38:03.480 回答
1

Your program doesn't erase parts of the array, it should simply not print the last part of it (if I'm reading your question correct).

For that you can keep another variable, containing the last usable index, and loop until you reach that instead.

If you really want to erase entries from an array, I suggest you to use std::vector instead.

于 2012-12-05T10:42:14.213 回答
0

从数组中删除并不容易,因为数组具有固定的大小(例如,5),该大小是在创建数组时确定的。

不要删除元素,而是将元素复制到同一个数组中以替换不需要的元素,例如:

// Move element 2 to element 1, erasing the old element 1
Track[1] = Track[2];
Track[2] = 0;

Another solution is to use a std::vector instead of an array. If Track2 is a vector, then you can use the vector::erase method to remove an element.

Another solution is to copy elements into a smaller array, for example:

// New temporary smaller array
int Temp[2];
// Copy elements we want to keep
Temp[0] = Track2[0];
Temp[1] = Track2[2];
于 2012-12-05T10:40:51.160 回答
0

There are ways to delete elements from an array, but you will not find a function that deletes all the elements at the end that are zero.

You need to take care of this yourself. What you need is to find the length of the array up to the last non-zero element. You can do this but traversing the array backwards:

int length;
for(length=Taille; i>=0; --length) {
   if (Track2[index] != 0) {
      break;
   }
}

lengthwill have the length of the array, and you can use this as upper bound in printing your array

于 2012-12-05T10:45:10.127 回答