下面是我要实现的功能
string* deleteEntry(string* dynamicArray, int& size, string entryToDelete);
// Precondition: dynamicArray point to a array of strings with give size,
// newEntry is a string
// Postcondition: The function should search dynamicArray for entryToDelete.
// If not found, the request should be ignored and the
// unmodified dynamicArray returned. If found, create a new
// dynamic array one element smaller than dynamicArray. Copy
// all element except entryToDelete into the new array, delete
// dynamicArray, decrement size, and return the new dynamic
// array
string* deleteEntry(string* dynamicArray, int& size, string entryToDelete)
{
for (int i=0;i<size,i++);
{
if (entryToDelete==dynamicArray[i])
{
delete[] entryToDelete;
}
}
}
很明显我是初学者,我不是找你来写我的代码,而是来给我建议如何删除条目。我在我的教科书上找不到它,我在网上找到的所有例子都包含一个单独的函数来完全完成这个,我觉得只需要一个函数就可以完成。
最佳答案
首先,您的 for
循环格式不正确。您需要在有逗号的地方使用分号,并且需要删除结尾的分号。
改变
for (int i=0;i<size,i++);
到
for (int i=0;i<size;i++)
其次,您不能delete[]
数组中的单个条目,因为它们不是用new[]
单独分配的(只有数组作为一个整体是)。
至于你的问题,答案就在你代码的注释中。您只是没有遵循概述的步骤:
// Postcondition: The function should search dynamicArray for entryToDelete.
// If not found, the request should be ignored and the
// unmodified dynamicArray returned. If found, create a new
// dynamic array one element smaller than dynamicArray. Copy
// all element except entryToDelete into the new array, delete
// dynamicArray, decrement size, and return the new dynamic
// array
你需要注意你的要求并按照他们说的去做,例如:
string* deleteEntry(string* dynamicArray, int& size, string entryToDelete)
{
// The function should search dynamicArray for entryToDelete...
for (int i = 0; i < size; ++i);
{
if (entryToDelete == dynamicArray[i]) // If found...
{
// create a new dynamic array one element smaller than dynamicArray...
string *newArray = new string[size-1];
// Copy all element except entryToDelete into the new array...
for(int j = 0; j < i; ++j)
newArray[j] = dynamicArray[j];
for(int j = i+1; j < size; ++j)
newArray[j-1] = dynamicArray[j];
// delete dynamicArray...
delete[] dynamicArray;
// decrement size...
--size;
// return the new dynamic array...
return newArray;
}
}
// If not found, return the unmodified dynamicArray...
return dynamicArray;
}
关于c++ - 如何使用 deleteEntry 函数删除数组中的单个字符串 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48489241/