删除和移动数组中的剩余元素C ++

时间:2017-04-22 02:49:10

标签: c++ arrays string

List.cpp(类定义)

我一直在研究有助于熟悉类的代码。我的代码目前有一个功能,可以显示用户的选项菜单。选项[1]假设添加一个字符串,选项[2]假设从列表中删除一个字符串,选项[3]打印字符串列表,选项[4]退出。我的选项[1]似乎工作正常,因为用户可以一次输入一个字符串,但我很难删除字符串。字符串当前存储在10个元素的数组中。我相信我为删除字符串编写的函数是可以的,因为我已经调试它并且看起来很成功,但是,我没有在控制台窗口看到结果。

我的数组位于我的类中的私有类中:字符串项[MAX_ITEMS];以及另一个名为:int totalItems;

的变量

然后使用switch case在我的main函数中调用该类:

//This code snippet below is located in a separate cpp file with main
cout << "Please enter the text you want to remove: " << endl;
cin >> userInput;
list1.remove(userInput);
////////////////////////////////////////////////////////////////////

//preprocessor directives
#include <iostream>
#include <string>

//header files
#include "list.h"

using namespace std;

List::List()
{
    //clear array prior to starting (set everything to NULL)
    for (int i = 0; i < MAX_ITEMS; i++)
    {
        items[i] = " ";
    }

    totalItems = 0;
}

//void List::init()
//{
//  string items[MAX_ITEMS];
//  totalItems = 0;
//}


bool List::insert(const string& data)
{

    //verifies that string is not empty, not in the list, and not full
    if (data.empty() == true || inList(data) == true || isFull() == true)
    {
        return false;
    }
    else
    {
        //      items[isFull)] = data;
        //      totalItems++;
        items[totalItems++] = data;
        return true;
    }
}


bool List::isEmpty() const
{
    //runs through loop to verify array is empty
    for (int i = 0; i < MAX_ITEMS; i++)
    {
        if (items[i].empty() != true)
        {
            return false;
        }
    }
    return true;
}

//identifies whether the string is full or not
bool List::isFull() const
{
    if (totalItems == MAX_ITEMS)
    {
        return true;
    }
    else
    {
        return false;
    }
}

//identifies whether the string is already in the list or not
bool List::inList(const string& theList)
{
    for (int i = 0; i < MAX_ITEMS; i++)
    {
        if (items[i] == theList)
        {
            return true;
        }
    }
    return false;
}

bool List::remove(const string& data)
{
    if (inList(data) == true || data.empty() == true)
    {
        return false;
    }

    for (int i = 0; i < MAX_ITEMS; i++)
    {
        if (items[i] == data)
        {
            items[i] == " ";
            for (int j = i; j < MAX_ITEMS; j++)
            {
                items[j] = items[j + 1];
                items[MAX_ITEMS - 1] == " ";
                break;
            }
        }
    }
    totalItems--;
    return true;
}

//prints list
void List::printList()
{
    for (int i = 0; i < MAX_ITEMS; i++)
    {
        cout << i << items[i] << '\t';
    }
}

list_test.cpp(main.cpp)

#include <iostream>
#include <string>

//header files
#include "list.h"

using namespace std;

//function prototypes
int showSelection();

int main()
{
    List list1;

    string userInput = "";
    int userChoice;

//  list1.init();

    userChoice = showSelection();

    while (userChoice != 4)
    {
        switch(userChoice)
        {
            case 1:
                cout << "Please enter the text you want to add: " << endl;
                cin >> userInput;
                list1.insert(userInput);

                /*if (list1.inList(userInput) == false)
                {
                    cout << "Text is already entered in the list!" << endl;
                }*/

                if (list1.isFull() == true)
                {
                    cout << "You have entered the MAXIMUM amount of elements!" << endl;
                }
                break;
            case 2:
                cout << "Please enter the text you want to remove: " << endl;
                cin >> userInput;
                list1.remove(userInput);
                break;
            case 3:
                cout << "Printed list: " << endl;
                list1.printList();
                break;
        }
        userChoice = showSelection();
    }

    cout << "Goodbye. Please press enter to exit." << endl;
    //TESTING PURPOSES FOR FUNCTIONS
    cout << list1.insert(userInput) << endl;
    cout << list1.isEmpty() << endl;
    cout << list1.isFull() << endl;
    cout << list1.inList(userInput) << endl;


    return 0;
}

/* ===========================================
Name: showSelection
Desc: displays menu for user to choose options
      for their inputted string(s).
Args: none
Retn: none
=========================================== */
int showSelection() 
{
    int userChoice;
    bool exit = false;

    while (exit == false)
    {
        cout << "\nTo select an option, please enter the corresponding number: " << endl;
        cout << "[1] to add a string" << endl;
        cout << "[2] to remove a string" << endl;
        cout << "[3] to print a string" << endl;
        cout << "[4] to exit" << endl << endl;
        cin >> userChoice;

        cout << "You entered option: " << userChoice << endl;
        cout << '\n';

        if (userChoice == 1 || userChoice == 2 || userChoice == 3 || userChoice == 4)
        {
            exit = true;
        }
        else
        {
            cout << "Invalid selection" << endl;
        }
    }`enter code here`
    return userChoice;
}

3 个答案:

答案 0 :(得分:1)

if (inList(data) == true || data.empty() == true)
{
    return false;
}

如果数据参数在列表对象中,则返回时不删除任​​何内容?这应该是!inList(data)

此外,当你进入此代码下面的循环时,这个循环:

for (int j = i; j < MAX_ITEMS; j++)
{
    items[j] = items[j + 1];
    items[MAX_ITEMS - 1] == " ";
    break;
}

只会执行j = i,&#34; break&#34;语句将停止执行此内部循环,并返回外部循环。

编辑:这就是我个人会解决这个问题的方法。

bool List::remove(const string& data)
{
    bool retVal;
    if (!inList(data) || data.empty())
    {
        retVal = false;
    }
    else{
        for (int i = 0; i < MAX_ITEMS; i++)
        {
            if (items[i] == data)
            {
                items[i] = " ";
                for (int j = i; j < (MAX_ITEMS - 1); j++)
                {
                    items[j] = items[j + 1];
                }
                items[MAX_ITEMS-1] = " ";
            }
        }
        totalItems--; 
        retVal = true;
    }
    return retVal;
}

答案 1 :(得分:1)

以下是您的代码应该如何显示:

bool List::remove(const string& data) {
    // only check if the list is empty so you don't nececarily go through it
    // you shoudn't ask here if the given string is in the list 
    // because you will search for it anyway just below
    if (data.empty()) 
        return false;

    for (int i = 0; i < MAX_ITEMS; ++i) {
        if (items[i] == data) { // now if it was found
            items[i] = " "; // set it to your empty value
            --totalItems; // prefix -- is faster then postfix one (no copy is created)
            for (int j = i; j < MAX_ITEMS - 1; ++j) { 
                // stop at j < MAX_ITEMS - 1 because you wouldn't want 
                // to swap last element with the next because there 
                // is none behind it
                if (items[j + 1] == " ")
                    // if the next item is already empty you don't need to shift any more
                    return true;

                // swap the next item with much more 
                // efficient std::swap function
                std::swap(items[j], items[j + 1]);
            }
            return true; // value is removed and items shifted so you can now return
        }
    }
    // if function gets to this point that means the value wasn't found
    return false;
}

如果您希望提高代码效率,我可以为您提供更多有关如何操作的建议。以上内容应该回答你的问题。

对这样的结构使用数组也不是最佳选择。使用链接列表意味着不需要转移。

编辑:用代码示例替换长文本 Edit2:如果不再需要转移,则添加return语句

答案 2 :(得分:1)

对我而言,由于无法运行完整代码,因此无法确定您要执行的操作。

但我认为这应该符合我的想法,你想做什么

dplyr
相关问题