Reputation: 1291
I am trying to remove a name from this array and then have an empty spot at the last position of the array once removed. How do I do this? Here is what I tried below. It removes it, but doesnt move to the end.
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;
}
Upvotes: 0
Views: 217
Reputation: 157324
Use the remove-erase idiom, with std::remove
and 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;
}
Upvotes: 2
Reputation: 3957
First of all, I think you'd much rather use a vector
or list
for this, that's what it has been designed for. But if you want to go this way, you could for example write a moveUp
method:
void moveUp(int startIndex, int endIndex, string* array) {
for (int ii = startIndex; ii < endIndex; ++ii) {
array[ii] = array[ii + 1];
}
array[endIndex] = 0;
}
Upvotes: 0
Reputation: 54971
With std::vector
, std::remove
, and std::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));
Upvotes: 0
Reputation: 6972
Here is one possible way to amend your current solution. I agree with ott--, though, you should probably use a list instead.
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;
}
}
Upvotes: 0
Reputation: 2708
Upvotes: 2