这是我要实现的功能

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/

10-15 08:55