2015-02-08 50 views
-2

尊敬的有用的StackOverflow用戶, 我有這個代碼在特定行中的功能Remove_Student(int section_id, int student_id)麻煩:C++表達式必須具有類類型

"(*iter).student_id[i].erase();". 

我收到該錯誤消息是表達式必須有一個類類型。 .erase的左邊必須有一個類/結構/聯合。然而,在我的Section類中,我已經將student_id定義爲int的向量。請,任何幫助將不勝感激,因爲我不明白爲什麼這不起作用。

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

}; 
+1

如果'student_id'是一個'vector ',那麼'student_id [i]'是一個'int',並且沒有成員函數。還要注意'std :: vector :: erase'沒有參數的重載。 – juanchopanza 2015-02-08 23:09:55

+1

請閱讀如何調用['std :: vector :: erase'](http://en.cppreference.com/w/cpp/container/vector/erase)。 – 2015-02-08 23:10:41

+0

@remyabel我有一個函數直接在它之上刪除會議時間的向量。會議時間是字符串,但擦除沒有參數,工作得很好。 – user3288305 2015-02-09 00:05:25

回答

1

(*iter).student_id[i]int,你可能想是這樣的:

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

雖然手寫循環有利於學習的目的,這是難以閱讀和維護。錯誤很容易做出來。優選的方法是使用標準庫中的方法,特別是使用std::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返回一個迭代器範圍的新的終端。如果它在內部使用std::find,則std::find將返回一個迭代器到該範圍的末尾(如果未找到)。

相關問題