Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When would you use an array rather than a vector/string?

I'm a beginner C++ programmer and so I've learnt using arrays rather than vectors (this seems to be the general way to do things, then move on to vectors later on).

I've noticed that a lot of answers on SO suggest using vectors over arrays, and strings over char arrays. It seems that this is the "proper" way to code in C++.

That all being said, when is it still worth using a classic array/char* (if ever)?

like image 941
Skilldrick Avatar asked Feb 27 '09 12:02

Skilldrick


2 Answers

When writing code that should used in other projects, in particular if you target special platforms (embedded, game consoles, etc.) where STL might not be present.

Old projects or projects with special requirements might not want to introduce dependencies on STL libraries. An interface depending on arrays, char* or whatever will be compatible with anything since it's part of the language. STL however is not guaranteed to be present in all build environments.

like image 196
Laserallan Avatar answered Oct 03 '22 09:10

Laserallan


Never.

If a raw array seems a better solution than a vector (for reasons other said here) then I use std::tr1::array or std::array in C++11 compilers (or boost::array). It simply does the checks I would do anyway to be sure and the size value usage makes DRY automatically implemented (for example I use the size in loops so that future changes of the array declaration will automatically work).

It's the array implementation "is" a raw array with checks and provided size constant anyway, so it's easy to get the array code in embedded code too because the code is not really "too smart" for any compiler. As far as the compiler support templates, I would copy the boost headers in my code to allow me to use this one instead of raw arrays. Because it's clearly too easy to make mistakes with raw arrays. Raw arrays are evil. They are error prone.

And it work very well with STL algorithms (if available).

Now, there is two cases where you need to use raw arrays (obligation) : when you're in C-only code (not communicating with C code, but writing in C-only part of code, like a C library). But then it's another language.

The other reason is when the compiler don't support templates at all...

like image 32
Klaim Avatar answered Oct 03 '22 10:10

Klaim