如何从数组中删除元素并将所有内容移动到某个位置?

时间:2013-05-03 17:49:42

标签: c++

我正在尝试从此数组中删除一个名称,然后在删除后在数组的最后位置有一个空位。我该怎么做呢?这是我在下面尝试的。它删除了它,但没有移动到最后。

const int array_size = 16;
string restaurants[array_size] = {"Texas Roadhouse","On The Border","Olive Garden","Panda       Express","Cracker Barrel","IHOP","Woohoo","Pei Wei","Mcdonalds","Denny's","Mrs. Fields","Subway","Dairy Queen","Burger King","Pizza Hut","Dominos"};
int current_size = 16;

cout << "Please enter the name of the Restaurant you would like to remove: ";
cin.ignore();
getline(cin, remove_restaurant);

remove(restaurants, restaurants_size, remove_restaurant);//function call

bool remove(string restaurants[], int& current_size, string name)//function to remove   array
{
    for (int i = 0; i < current_size; i++)//look at each name you want to remove
    {
        if ( restaurants[i] == name)
        {
        restaurants[i]=restaurants[i+1];
        current_size --;
        cout << "Restaurant removed successfully." << endl;
        return true;            
        }
    }
return false;
}

5 个答案:

答案 0 :(得分:2)

  1. 创建与原始
  2. 相同大小的数组
  3. 开始迭代原始数组的元素
  4. 如果数组中的当前项不等于要删除的项,请将其添加到新数组

答案 1 :(得分:2)

使用移除 - 删除惯用法,std::removestd::fill

bool remove(string restaurants[], int& current_size, string name)//function to remove   array
{
    auto begin = std::begin(restaurants);
    auto end = std::next(begin, current_size);
    auto new_end = std::remove(begin, end, name);
    std::fill(new_end, end, {});
    current_size = std::distance(begin, new_end);
    if (new_end != end) {
        std::cout << "Restaurant removed successfully." << std::endl;
    }
    return new_end != end;
}

答案 2 :(得分:0)

以下是修改当前解决方案的一种可能方法。我同意ott--,你应该使用一个列表。

for (int i = 0; i < current_size; i++)//look at each name you want to remove
{
  if (restaurants[i] == name) {
    swap(restaurants[i], restaurants[current_size-1]);
    current_size --;
    cout << "Restaurant removed successfully." << endl;
    return true;
  }
}

答案 3 :(得分:0)

使用std::vectorstd::removestd::vector::erase

#include <algorithm>
#include <string>
#include <vector>

// ...

vector<string> restaurants { ... };

string remove_restaurant;
getline(cin, remove_restaurant);

restaurants.erase
  (remove(restaurants.begin(), restaurants.end(), remove_restaurant));

答案 4 :(得分:0)

首先,我认为您更倾向于使用vectorlist,这就是它的设计目标。但是如果你想这样做,你可以写一个moveUp方法:

 void moveUp(int startIndex, int endIndex, string* array) {
     for (int ii = startIndex; ii < endIndex; ++ii) {
         array[ii] = array[ii + 1];
     }

     array[endIndex] = 0;
 }