xcode 删除数组C++中的元素,复制另一个元素

zrfyljdw  于 2023-05-08  发布在  其他
关注(0)|答案(1)|浏览(123)

我正在做一个学校的项目,被从数组中删除元素的最佳方法卡住了。不幸的是,项目要求不允许我们使用向量。我可以摆脱我需要的元素(A3),但是当我的代码运行时,它会把最后一个元素放在它的位置上,而不是只是将所有元素向前移动一个。项目要求非常具体,只允许我将studentID作为函数的输入。
下面是函数之后的结果(注意A5现在在2和4中):

Student ID   First Name  Last Name   Email Address   Age     Days In Courses     Degree Program
A1  John    Smith   John1989@gm ail.com 20  30,35,40    Security
A2  Suzan   Erickson    Erickson_1990@gmailcom  19  50,30,40    Network
A5  Dyllan  Hackett dhack27@gmail.com   30  14,4,25 Software
A4  Erin    Black   Erin.black@comcast.net  22  50,58,40    Security
A5  Dyllan  Hackett dhack27@gmail.com   30  14,4,25 Software

我需要它来展示:

Student ID   First Name  Last Name   Email Address   Age     Days In Courses     Degree Program
A1  John    Smith   John1989@gm ail.com 20  30,35,40    Security
A2  Suzan   Erickson    Erickson_1990@gmailcom  19  50,30,40    Network
A4  Erin    Black   Erin.black@comcast.net  22  50,58,40    Security
A5  Dyllan  Hackett dhack27@gmail.com   30  14,4,25 Software

下面是我正在尝试的代码,任何帮助都表示感谢!疯狂地尝试不同的东西。
roster.cpp

//
//  roster.cpp
//  DyllanHackett_C867
//
//  Created by Dyllan Hackett on 4/28/23.

#include <iostream>
#include <string>
#include <vector>
#include <regex>
#include "roster.h"
#include "student.h"
#include "degree.h"

using namespace std;

// Remove student_ID
void Roster::remove(string studentID){
    int j;
    int found = 0;
    int tot = 5;
    for (int i = 0; i < 5; i++) {
        if (classRosterArray[i]->getStudentID() == studentID) {
            for (j=i; j <(tot -1);j++) {
                classRosterArray[j] = classRosterArray[j + i];
                found++;
                i--;
                tot--;
            }
        }
    }
    if (found == 0)
        cout << "StudentID not found in roster.\n";
    else
            cout << "StudentID removed.\n";
    cout << endl;
}
nfzehxib

nfzehxib1#

要在序列中移动所有内容,代码应该类似于arr[i] = arr[i + 1],我很肯定您已经知道了。
因此,尝试在remove函数的内部循环中为您正在操作的索引放置一些输出语句,以证明(或反驳)您正在做类似于上面代码的事情。

for (int i = 0; i < 5; i++) {
        if (classRosterArray[i]->getStudentID() == studentID) {
            for (j=i; j <(tot -1);j++) {
                classRosterArray[j] = classRosterArray[j + i];
                found++;
                i--;
                tot--;
            }
        }
    }

相关问题