0

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

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;
}
4

5 回答 5

2
  1. 创建一个与原始大小相同的数组
  2. 开始迭代原始数组的元素
  3. 如果数组中的当前项不等于要删除的项,则将其添加到新数组中
于 2013-05-03T17:54:20.603 回答
2

使用 remove-erase 成语,with std::removeand std::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;
}
于 2013-05-03T17:58:42.650 回答
0

首先,我认为您更愿意为此使用vectoror list,这就是它的设计目的。但是,如果您想这样做,例如可以编写一个moveUp方法:

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

     array[endIndex] = 0;
 }
于 2013-05-03T18:02:46.303 回答
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;
  }
}
于 2013-05-03T17:58:48.570 回答
0

, std::vector,std::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));
于 2013-05-03T17:59:19.207 回答