Vector

Hi for some reason this crashes for me

1
2
3
4
5
6
struct Struct
{
	char*	NAME;
    int		OBJ;
};
std::vector<Struct> Logged;


1
2
3
4
for(int i = 0; i < 50; i++){
	Logged[i].NAME = "test";
	Logged[i].OBJ = 12345;
}


whats am i doing wrong with that?

here is a image of what happens when i debug it
http://i.imgur.com/U5qrH.png
Last edited on
if you want to store 50 elements in your vector Logged you need to tell the vector:

std::vector<Struct> Logged(50);

So you can use up to 50 elements. It'd be better to use push_back():

http://www.cplusplus.com/reference/stl/vector/push_back/
what if i dont know how big i want the vector to be?
i dont think i can use the push_back for this as the way i need to read it
what if i dont know how big i want the vector to be?
Then use push_back.

i dont think i can use the push_back for this as the way i need to read it
You can use push_back for this.
Last edited on
You can use push_back.
1
2
3
4
5
6
for(int i = 0; i < 50; i++){
	Struct temp;
	temp.NAME = "test";
	temp.OBJ = 12345;
	Logged.push_back(temp);
}


In C++11 you can use emplace_back and avoid having to create a temp object.
1
2
3
for(int i = 0; i < 50; i++){
	Logged.emplace_back("test", 12345);
}
thanks guys

but push_back still dont really work for me unless you know how to do it better
because i need to be able to know where abouts each objects are in the vector. an then i need to be able to reset that vector again an not put it on the end of the vector
push_back is for adding objects to the end.

Your other problem is completely different. Sounds like you need to think a bit and come up with something like this:

Get new object.
Look through vector to see if this is a new one or not.
If new, push_back onto the end.
If not new, replace existing one.
Last edited on
a named object sounds like something a map could deal with
Topic archived. No new replies allowed.