C++ 表达式必须有 Class 类型

C++ Expression Must Have Class Type

亲爱的乐于助人的 Whosebug 用户, 我在函数 Remove_Student(int section_id, int student_id):

的特定行中遇到此代码的问题
"(*iter).student_id[i].erase();".  

我收到的错误消息是表达式必须具有 class 类型。 .erase 的左边必须有一个 class/struct/union。但是,在我的 class 部分中,我已经将 student_id 定义为整数向量。拜托,任何帮助将不胜感激,因为我无法弄清楚为什么这不起作用。

#pragma once
#include <vector>
#include <iostream>
#include <string>

using namespace std;

class Section
{
public:
friend class University;


private:
    int section_id;
    string course_id;
    string instructor;
    vector<string> meeting_time;
    vector<int> student_id;
    string location;


};








#pragma once
#include <vector>
#include <string>
#include <iostream>
#include "Section.h"
#include "misc.h"

using namespace std;

class University{
public: 
    string Add_Section(int section_id, string course_id, string instructor, string location){
        Section newSection;
        newSection.section_id = section_id;
        newSection.course_id = course_id;
        newSection.instructor = instructor;
        newSection.location = location;
        sections.push_back(newSection);
        return intToString(section_id) + "was added\n";
    }


    string Remove_Student(int section_id, int student_id)
    {
        vector<Section>::iterator iter;
        iter = sections.begin();
        while (iter != sections.end())
        {
            if (section_id == (*iter).section_id)
            {
                for (unsigned int i = 0; i < (*iter).student_id.size(); i++)
                {
                    if ((*iter).student_id[i] == student_id)
                    {
                        (*iter).student_id[i].erase();
                        return student_id + " was removed.\n";
                    }
                }
                return intToString(student_id) + " was not found.\n";
            }

            else
            {
                iter++;
            }

        }
        return intToString(section_id) + " was not found.\n";
    }



private:
    vector<Section> sections;

};

(*iter).student_id[i] 指的是一个 int,你可能想要这样的东西:

(*iter).student_id.erase((*iter).student_id.begin() + i);

尽管手写循环对学习很有帮助,但它很难阅读和维护。很容易犯错误。首选方法是使用标准库中的方法,特别是 std::remove。 erase-remove 习惯用法极大地简化了您的代码。这是一个例子:

int main()
{
    std::vector<int> v{1, 2, 1, 2, 1};
    std::vector<int>::iterator remove_it = std::remove(v.begin(), v.end(), 1);
    if (remove_it == v.end()) std::cout << "Student not found.\n";
    else
    {
        v.erase(remove_it, v.end());
        std::cout << "Student removed.\n";
    }
}

sdt::remove returns 到范围新结束的迭代器。如果它在内部使用 std::find,如果没有找到,std::find returns 一个指向范围末尾的迭代器。