gpt4 book ai didi

c++ - 如何从 vectors vector 中删除一个元素?

转载 作者:行者123 更新时间:2023-11-28 05:07:02 26 4
gpt4 key购买 nike

我在按索引从“组”中删除“成员”时遇到问题:

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

错误::将“const std::vector”作为“this”参数传递会丢弃限定符 [-fpermissive] group[_group].getMember().erase(group[_group].getMember().begin() + 1 );

有人可以帮帮我吗?

最佳答案

问题出在这里:

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

getMember() 函数(我建议将其称为 getMembers())返回一个 const vector 引用。 p>

由于 constness,编译器会阻止修改。

您可以通过以下方式修复重构:

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

关于c++ - 如何从 vectors vector 中删除一个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44458133/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com