尝试通过多个向量访问变量时,向量下标超出范围

vector subscript out of range when try to acess a variable through multiple vectors

本文关键字:向量 下标 范围 变量 访问      更新时间:2023-10-16

在发布此错误之前,我已经检查过我没有试图访问超出范围的向量的成员,是的,向量的第一个成员以索引0开始,以(向量大小-1(结束

我已经去掉了不相关的代码来显示我的错误。

Voter v1("Ailee", 100, "Engineering", 012, d1, PositionType::Normal);
if (v1.getName() == "Ailee")
{
cout << "nTrue1n";   // Yes
}
BallotPaper bp1(PositionType::President);
v1.AddBallotPaper(bp1);
if (v1.getBallotPaper(0).getPositionBP() == PositionType::President)
{
cout << "nTrue2n"; //Yes
}
Candidate c1("Kookie", 100, "Engineering", 012, d1,  PositionType::Normal);
bp1.AddCandidate(c1);
if (bp1.getCandidate(0).getName() == "Kookie")
{
cout << "nTrue3n";    // Yes
}
//cannot reach to candidate
if (v1.getBallotPaper(0).getCandidate(0).getName() == "Kookie")
{
cout << "nTrue4n";   //error!
}

这是我的相关类的源文件:选民类别:

class Voter :public Member
{
private:
std::vector<BallotPaper> _bp;  //use vector for simple iteration
public:
Voter::Voter(std::string a, int b, std::string c, int d, Date e, PositionType f) : Member(a, b, c, d, e, f){}
void Voter::AddBallotPaper(BallotPaper b)
{
_bp.push_back(b);
}
BallotPaper Voter::getBallotPaper(int index)
{
return _bp[index];
}
}

用于选票纸类:

class BallotPaper
{
private:
PositionType _positionbp;
std::vector<Candidate> _candidatesbp;   // only contain the required candidate
public:
BallotPaper::BallotPaper(PositionType a)
{
_positionbp = a;
}
void BallotPaper::AddCandidate(Candidate c)
{
_candidatesbp.push_back(c);
}
PositionType BallotPaper::getPositionBP()
{
return _positionbp;
}
Candidate BallotPaper::getCandidate(int index)
{
return _candidatesbp[index];
}
}

候选人类别:

class Candidate :public Member
{
private:
int _votecount;
PositionType _position;
public:
Candidate::Candidate(std::string a, int b, std::string c, int d, Date e, PositionType f) : Member(a, b, c, d, e, f)
{
_votecount = 0;
}
}

父类:成员文件

Member::Member(std::string name, int id, std::string course, int contact, Date joindate, PositionType currentposition)
{
_name = name;
_id = id;
_course = course;
_contact = contact;
_joindate = joindate;  //in the format of 2018/10/22
_currentposition = currentposition;
}
void Member::setName(std::string name)
{
_name = name;
}
std::string Member::getName()
{
return _name;
}

它似乎无法从类的向量的向量中获取成员变量。我们非常感谢您的任何意见!

当您将某个东西push_back到一个向量中时,您会生成一个副本。

此行:v1.AddBallotPaper(bp1);创建bp1的副本,并将其附加到v1内部的向量中
稍后,当您通过执行bp1.AddCandidate(c1);更改bp1时,存储在v1中的副本不受影响。