2017-06-09 126 views
0

我必須由索引從一個「組」刪除「成員」的問題:如何擦除矢量矢量中的元素?

#include <vector> 
#include <string> 
using namespace std; 

class Member 
{ 
    public: 
    explicit Member(const string &name, const unsigned long &key) : m_name(name), m_key(key) {} 
    const string &getName() const {return m_name;}; 
    const unsigned long &getKey() const {return m_key;}; 

    private: 
    string m_name; 
    unsigned long m_key; 
}; 
//------------------------------------------------------------------------ 
class Group 
{ 
public: 
    explicit Group(const string &name) : m_name(name) {} 
    const string &getName() const {return m_name;}; 
    void addMember(const Member &member) {m_member.push_back(member);}; 
    const vector<Member> &getMember() const {return m_member;}; 

    private: 
    string m_name; 
    vector<Member> m_member; 
}; 

void main() { 
    vector<Group> group; 
    group.push_back(Group("Membergroup 1")); 
    group[0].addMember(Member("Mark", 123456)); 
    group[0].addMember(Member("John", 234567)); 
    group[0].getMember().erase(group[0].getMember().begin() + 1); //to delete John 
} 

錯誤::使「常量性病::矢量」作爲「本」的說法丟棄限定符[-fpermissive]組[_group] .getMember()。erase(group [_group] .getMember()。begin()+ 1);

有人可以幫我嗎?

回答

1

問題是這裏:

const vector<Member> &getMember() const {return m_member;}; 

函數getMember()(我建議作爲getMembers()調用)返回一個常量參考矢量。

由於constness,編譯器會阻止修改。

您可以修復下列方式只是重構:

class Group 
{ 
public: 
    // ... 
    const vector<Member>& getMembers() const { return m_member; } 
    vector<Member>& getMembers() { return m_member; } 
    // ...