簡體   English   中英

如何從向量中查找和刪除對象?

[英]How to find and remove an object from a vector?

我有一個名為GradeBook的類,並且已經在該類中定義了包含學生ID,姓名和等級的對象。 我的代碼的這一部分正常工作,並將對象存儲到向量中並正確打印。 我已經嘗試了幾個小時,無法弄清或找到如何獲取用戶輸入的整數,查找它是否與向量中的學生ID匹配並刪除相應的行。

我的代碼:

int main(){
...
int userinput;
vector <GradeBook> vec;  //named vector "vec"

GradeBook gradeBook1(1, "Bob", 72.3); //created an object in GradeBook
vec.push_back(gradeBook1);    //object contains ID#, name, grade
GradeBook gradeBook2(4, "Jim", 85.4);
vec.push_back(gradeBook2);
GradeBook gradeBook3(2, "Rob", 99.6);
vec.push_back(gradeBook3);
GradeBook gradeBook4(3, "Ron", 89.7);
vec.push_back(gradeBook4);
GradeBook gradeBook5(5, "Jon", 66.9);
vec.push_back(gradeBook5);

cout << "Enter the ID# of student you want to remove: ";
cin >> userinput;

vector <GradeBook>::iterator it;     //this is where i'm having trouble
for (it = vec.begin(); it != vec.end(); it++) { 
        if ( it == userinput ){     //I get a bunch of errors here
        //i'm not sure how to equate the user input to the iterator
            vec.erase(vec.begin()+userinput);
        else
        {
        cout << "ID # not found" << endl;
        }
}

....
return 0;
}

更新

感謝您的所有評論,我將所有評論都考慮在內,最終修復了我的代碼。 現在,它讀取用戶輸入的ID#並找到包含它的對象。 但是,它仍然無法正常工作。

這是我的新代碼:

cout << "enter ID to remove" << endl;
cin >> userinput;

vector <GradeBook>::iterator it3;
for (it3 = vec.begin(); it3 != vec.end(); ++it3) {
    if ( it3->studentID == userinput ){    
        vec.erase(vec.begin()+userinput)
    }
    else
    {
        cout << "ID # not found" << endl;
    }
}

我輸入了要刪除的ID#3作為測試。 這將循環直到正確找到具有我輸入的ID號的對象,但這是它提供的輸出:

ID# not found
ID# not found
ID# not found
ID# not found

它在那里停止,因為在我的程序中,3是列表中的第4個ID號。 誰能看到我的代碼出了什么問題? 為什么這樣做呢?

我想您想按以下方式完成它:

  1. 如果輸入了任何ID,請刪除所有ID,並且不打印任何消息。
  2. 如果找不到ID,請打印出錯誤消息。

實現這些要求的代碼如下:

cout << "enter ID to remove" << endl;
cin >> userinput;

bool isFound = false;
vector <GradeBook>::iterator it3;
for (it3 = vec.begin(); it3 != vec.end(); ++it3) {
    if (it3->studentID == userinput) {
        it3 = vec.erase(it3); // After erasing, it3 is now pointing the next location.
        --it3; // Go to the prev location because of ++it3 in the end of for loop.
        isFound = true;
    }
}

if (!isFound) {
    cout << "ID # not found" << endl;
}

在vector :: erase刪除元素之后,傳遞給函數的迭代器將失效。 因此,您應該獲得一個新的迭代器vector :: erase返回。 有關更多詳細信息,請檢出: vector :: removestd :: vector迭代器無效

該代碼可以工作,但是我建議使用前面提到的std :: removestd :: remove_if ,因為它們使代碼更易於閱讀和維護。 (請參閱--it3;行。)此外,它們的運行速度可能更快。

您可以使用std::removestd::remove_if

vec.erase(std::remove(vec.begin(), vec.end(), userinput), vec.end());

如果要刪除的項目需要滿足其他條件,則可以使用std::remove_if

vec.erase(std::remove_if(vec.begin(), vec.end(), [](auto item) { ... }), vec.end());

現在,您正在將迭代器的數據位置與用戶輸入進行比較。 你寫的地方

 if ( it == userinput )

嘗試寫作

 if ( it->ID == userinput )

假設您的id字段名為ID

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM