Archived

This topic is now archived and is closed to further replies.

Drakon

Vector resizes, but previous information doesn't go away.

Recommended Posts

When I use the .erase(iterator) on a vector, the vector will be resized, but I can still access what I''ve deleted. Example, if vector Blah had 5 ints(5 being accessed by Blah[4]), each with a value of 10, and I delete one of them. Now it has 4, and I can stil get 10 by using Blah[4]. I''m not quite sure if this is even a problem yet, actually, but I do want to avoid having useless numbers floating around.

Share this post


Link to post
Share on other sites
I''m not an expert, but I think when you access Blah[4], it is actually no longer available to you, but the data is still held in the same place. It doesn''t go away until it''s overwritten, and it just means that you should no longer have access to it (and your OS has permission to overwrite it).

You shouldn''t be accessing Blah[4] anyway.

Share this post


Link to post
Share on other sites
Well don''t do that then.

As far as I''m aware, vectors don''t normally shrink (allocation-wise) by themselves. This means that the extra elements still exist, they just aren''t in the length of the vector (i.e. between begin() and end()) any more.

Don''t reference ones beyond size() - 1 . Simple as that.

Mark

Share this post


Link to post
Share on other sites
Yeah, thats why I wasn''t sure if it was going to be a problem or not. But, would it take less memory if unused integer space was set to 0 rather than big numbers? I have a vector of classes which will probably become quite large and numerous, and getting rid of them will be a frequent occurrence. As I said before, I dont want lots of unused info floating around.

But thanks for the help, too.

Share this post


Link to post
Share on other sites
That''s undefined behavior. You told it you didn''t need the fourth element any more, and then you went and looked at it anyway. This time is happen to still be there, and nothing bad happened to your program. That''s the whole rub with undefined behavior, it can "work" in certain scenarios but it''s not gauranteed to work when you run the same executable twice in a row much less when anything changes. It could work, it could whack your hard-drive, it could throw an exception, it''s "undefined".

So you should never do that, and debug builds of many STL libraries will perform bounds-checks on vector accesses (and give you an error).

Share this post


Link to post
Share on other sites