简体   繁体   English

如何从向量中查找和删除对象?

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

I have a class named GradeBook and I already have the objects defined in the class that contained student ID, name and grade. 我有一个名为GradeBook的类,并且已经在该类中定义了包含学生ID,姓名和等级的对象。 This part of my code works correctly and it stores the objects into the vector and prints properly. 我的代码的这一部分正常工作,并将对象存储到向量中并正确打印。 I've been trying for hours and cannot figure out or find how to take a user input integer, find if it matches the student ID in the vector and remove the corresponding row. 我已经尝试了几个小时,无法弄清或找到如何获取用户输入的整数,查找它是否与向量中的学生ID匹配并删除相应的行。

My Code: 我的代码:

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;
}

UPDATE 更新

Thank you for all of your comments, I took all of them into consideration and ended up fixing my code. 感谢您的所有评论,我将所有评论都考虑在内,最终修复了我的代码。 Now, it reads the user input ID# and finds the object that contains it. 现在,它读取用户输入的ID#并找到包含它的对象。 However, it still doesn't work properly. 但是,它仍然无法正常工作。

Here is my new code: 这是我的新代码:

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;
    }
}

I entered the ID# 3 to be removed as a test. 我输入了要删除的ID#3作为测试。 This loops until it correctly finds the object that has the ID number I enter but this is the output it gives: 这将循环直到正确找到具有我输入的ID号的对象,但这是它提供的输出:

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

It stops there because in my program, 3 is the 4th ID number on the list. 它在那里停止,因为在我的程序中,3是列表中的第4个ID号。 Can anyone see what's wrong with my code? 谁能看到我的代码出了什么问题? Why is it doing that? 为什么这样做呢?

I guess you want to get it done as follows: 我想您想按以下方式完成它:

  1. If there are any IDs that you've entered, remove all of them and don't print out any message. 如果输入了任何ID,请删除所有ID,并且不打印任何消息。
  2. If no ID is found, print out an error message. 如果找不到ID,请打印出错误消息。

The code implementing these requirements is as follows: 实现这些要求的代码如下:

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;
}

After vector::erase remove the element, the iterator passed to the function is invalidated. 在vector :: erase删除元素之后,传递给函数的迭代器将失效。 So you should get a new iterator vector::erase returns. 因此,您应该获得一个新的迭代器vector :: erase返回。 For more details, Check out: vector::remove , std::vector iterator invalidation . 有关更多详细信息,请检出: vector :: removestd :: vector迭代器无效

This code works, but I recommend using std::remove and std::remove_if as mentioned before because they make code easier to read and maintenance. 该代码可以工作,但是我建议使用前面提到的std :: removestd :: remove_if ,因为它们使代码更易于阅读和维护。 (See --it3; line.) In addition, they may run faster. (请参阅--it3;行。)此外,它们的运行速度可能更快。

You can use std::remove or std::remove_if . 您可以使用std::removestd::remove_if

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

If the items to be removed need to satisfy some other criteria, you can use std::remove_if . 如果要删除的项目需要满足其他条件,则可以使用std::remove_if

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

Right now, you're comparing the data location of the iterator to the user input. 现在,您正在将迭代器的数据位置与用户输入进行比较。 Where you have written 你写的地方

 if ( it == userinput )

try writing 尝试写作

 if ( it->ID == userinput )

assuming that your id field is named ID . 假设您的id字段名为ID

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM