C ++数组排序,如何在数组末尾加-1?

时间:2014-04-17 22:27:49

标签: c++ arrays function

我目前正在开发一个C ++项目。我被困在一个我必须写的功能上。函数名称是删除。该函数的目的是通过将所有元素移回一个位置来删除给定索引处的列表中的值,-1替换列表末尾的元素。我已经完成了这个函数的移位部分,我只是坚持我如何把-1放在我的数组的末尾。 这是我的代码:

void remove(int vals[], int sz, int index)
{
  for(int i = index ; i < (sz-1); ++i)
  {
   vals[i] = vals[i+1];
  }
  vals[sz - 1] = -1;



} 

1 个答案:

答案 0 :(得分:2)

如果我理解你的问题,我相信你需要:

void remove(int vals[], int sz, int index)
{
  //I altered your loop here as the line inside it would have accessed past the
  //end your array. I am assuming sz is the number of elements in the array
  for(int i = index ; i < sz - 1; ++i)
  {
   vals[i] = vals[i + 1]; 

  }
  //This sets the last element in your array to -1
  vals[sz - 1] = -1;
} 

希望这有帮助。

编辑:正如其他人所说,如果你想添加和删除元素,你可能会更好地使用STD容器之一,比如std :: vector而不是C风格的数组。