如何从数组中删除一个元素并将所有元素向上移动一个位置
How do I remove an element from an array and move everything up a spot?
我试图从这个数组中删除一个名称,然后在数组的最后一个位置有一个空点。我该怎么做呢?下面是我的尝试。它会删除它,但不会移动到末尾。
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;
}
使用删除-擦除习语,std::remove
和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;
}
- 创建一个与原始 相同大小的数组
- 开始迭代原始数组的元素
- 如果数组中的当前项不等于要删除的项,则将其添加到新数组
这是修改当前解决方案的一种可能方法。我同意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;
}
}
与std::vector
, std::remove
, 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));
首先,我认为您更愿意使用vector
或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;
}
相关文章:
- lower_bound()返回最后一个元素
- 基于范围的 for 循环:迭代使用一个元素扩展的向量
- 使用运算符 [] 引用 std::vector 上最后一个元素时出现问题<>
- Lower_bound不适用于具有 3 个元素的向量的最后一个元素
- 检查 2D 网格的某个元素是否与另一个元素共享对角线、水平线或垂直线
- 仅显示链表的最后一个元素
- push_back通过自行创建的对象获取最后一个元素的向量
- 使用 map.end() 访问 map 的最后一个元素
- 如何知道地图中的最后一个元素是否被删除?
- 选择一个元素而不是一个对象的数组的原因
- std::矢量保存 只推送最后一个元素
- 为什么这个选择排序算法仍然切换一个元素,当它已经是其他元素中最小的元素时?
- 反转后不返回最后一个元素
- 如何在新数组较小时创建新数组并将旧数组的最后一个元素复制到新数组中?
- 访问 for_each 函数中的前一个元素
- 在 QListView 中显示最后一个元素
- 从 std::vector 中选择一个元素,而不是给定元素
- C++:在进行切片时对迭代器的约定,特别是对于访问最后一个元素并最终将其删除
- 遍历列表包含排除最后一个元素的内容
- 如何从一个无序集合中获取一个元素