【发布时间】:2022-01-16 22:42:27
【问题描述】:
这是我的代码,我无法找到删除数组中所有 Apple elem 的方法。我能够数出数组中的苹果数。我希望有人可以帮助...
string items[10] = { "Apple", "Oranges", "Pears", "Apple", "bananas", "Apple", "Cucumbers", "Apple", "Lemons", "Apple" };
//Counts the total amount of apples
int n = sizeof(items) / sizeof(items[0]);
cout << "Number of times Apple appears : "
<< count(items, items + n, "Apple");
//remove the element Apple from array
if (string items[].contains("Apple"))
{
items[].remove("Apple");
}
【问题讨论】:
-
您想对删除的项目做什么?因为删除它们后您仍然会有一个包含 10 个元素的数组。如果您使用的是
std::vector,您可以提醒他们并使用std::erase_if缩小向量。 -
您永远无法“删除”数组中的元素。
-
无关:
sizeof(items) / sizeof(items[0]);返回size_t,而不是int所以auto n =std:size(items);` 会很好