Probably a stupid question, but when should you choose to use an array over something like a vector (or ArrayList in Java)?
Just a note: I'm coming from the Java standpoint moving into C++, so the world is slightly alien to me.
array vs vector
Moderator: Coders of Rage
-
- Respected Programmer
- Posts: 387
- Joined: Fri Dec 19, 2008 3:33 pm
- Location: Dallas
- Contact:
Re: array vs vector
In C++ the std::vector is closer to a standard contiguously allocated array type. There is penalty for out of order insertion, out of order access and resizing. If you treat an std::vector similarly to a regular ol' array, you won't see much difference in performance.
std::list is closer to the ArrayList implementation which is a linked list structure. There's minimal penalty for out of order insertion/deletion, and indexing into them is slower but fairly consistent. They can grow at runtime with minimal penalty.
Use vector where there's not much chance for resizing/inserting excessively and where runtime performance is desired.
Use list where random access trumps performance.
std::list is closer to the ArrayList implementation which is a linked list structure. There's minimal penalty for out of order insertion/deletion, and indexing into them is slower but fairly consistent. They can grow at runtime with minimal penalty.
Use vector where there's not much chance for resizing/inserting excessively and where runtime performance is desired.
Use list where random access trumps performance.
- Falco Girgis
- Elysian Shadows Team
- Posts: 10294
- Joined: Thu May 20, 2004 2:04 pm
- Current Project: Elysian Shadows
- Favorite Gaming Platforms: Dreamcast, SNES, NES
- Programming Language of Choice: C/++
- Location: Studio Vorbis, AL
- Contact:
Re: array vs vector
And please use a regular-ol, static array for when you don't need dynamic resizing at runtime.
I see far too many people these days who abuse the shit out of STL and dynamic containers when a static buffer would be faster and/or have much less overhead. If you are of the mindset "why do I care about a few extra bytes," then why the hell are you using C/++ anyway?
I see far too many people these days who abuse the shit out of STL and dynamic containers when a static buffer would be faster and/or have much less overhead. If you are of the mindset "why do I care about a few extra bytes," then why the hell are you using C/++ anyway?