我想从这个数组中删除一个名称,然后在数组的最后一个位置删除一个空位。我该怎么做呢?这是我在下面尝试的。它将其删除,但不会移动到最后。如何从阵列中删除元素并将所有元素都移动到某个点上?
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;
}
使用列表而不是数组。 – 2013-05-03 17:51:13
具体来说,使用STL的std :: list – 2013-05-03 17:52:41
这只是勉强的C++(cout/cin&inline声明)。建议使用STL容器,以使其成为C++解决方案。 – 2013-05-03 18:04:05