How to erase an element from a vectors vector?

时间:2017-06-09 12:41:11

标签: c++ vector std erase

i have a problem to delete an "Member" from a "Group" by index:

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

Error: : passing 'const std::vector' as 'this' argument discards qualifiers [-fpermissive] group[_group].getMember().erase(group[_group].getMember().begin() + 1);

Can someone help me please?

1 个答案:

答案 0 :(得分:1)

The problem is here:

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

The function getMember() (which I suggest to call as getMembers()) returns a const reference to the vector.

Since constness, the compiler prevents modifications.

You can fix just refactoring in the following way:

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