[英]Accessing vector in class in vector
I feel as though I'm going about this the right way, but I keep getting the error "EXC BAD ACCESS" 我觉得我正在以正确的方式解决这个问题,但我不断收到错误“EXC BAD ACCESS”
I have a class person
, fairly simple with everything public. 我有一类
person
,一切公共相当简单。
class person
{
public:
int id;
vector<float> scores;
float avgscore;
};
I then make a vector of person
s using the new operator 然后我使用new运算符制作一个
person
的向量
vector<person> *people = new vector<person>[num_persons];
I then attempt to access the vector inside the class person
然后我尝试访问类
person
内部的向量
(*people)[current_person].scores.push_back(temp);
where current_person
=0, and temp
is an integer. 其中
current_person
= 0, temp
是整数。
Am I handling the vector the right way? 我是以正确的方式处理矢量吗?
Try this: 尝试这个:
vector<person> people(num_persons);
and then... 接着...
people[current_person].scores.push_back(temp);
This line 这条线
vector<person> *people = new vector<person>[num_persons];
new vector only creates a vector but it contains 0 elements, accessing to (*people)[0]
is undefined behavior which your error message EXC BAD ACCESS
tells the story. 新向量只创建一个向量,但它包含0个元素,访问
(*people)[0]
是未定义的行为,您的错误消息EXC BAD ACCESS
告诉故事。 You still need to add person element to people visiting it, eg 您仍然需要向访问它的人添加person元素,例如
person p1;
people->push_back(p1); // add element to vector
(*people)[0].scores.push_back(temp); // now you are ok to visit first element.
// don't forget to delete vector at right place
delete people;
As you are using vector already, you could just continue using vector for people instead of using the raw pointer. 由于你已经使用了vector,你可以继续使用vector而不是使用原始指针。
std::vector<person> people;
person p1;
people.push_back(person);
people[position].scores.pus_back(score);
// don't need to worry releasing people memory anymore.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.