5

Well, after a full year of programming and only knowing of arrays, I was made aware of the existence of vectors (by some members of StackOverflow on a previous post of mine). I did a load of researching and studying them on my own and rewrote an entire application I had written with arrays and linked lists, with vectors. At this point, I'm not sure if I'll still use arrays, because vectors seem to be more flexible and efficient. With their ability to grow and shrink in size automatically, I don't know if I'll be using arrays as much. At this point, the only advantage I personally see is that arrays are much easier to write and understand. The learning curve for arrays is nothing, where there is a small learning curve for vectors. Anyway, I'm sure there's probably a good reason for using arrays in some situation and vectors in others, I was just curious what the community thinks. I'm an entirely a novice, so I assume that I'm just not well-informed enough on the strict usages of either.

And in case anyone is even remotely curious, this is the application I'm practicing using vectors with. Its really rough and needs a lot of work: https://github.com/JosephTLyons/Joseph-Lyons-Contact-Book-Application

JosephTLyons
  • 2,075
  • 16
  • 39
  • 1
    `vector`'s convenience comes at a price. – T.C. Jun 29 '16 at 04:44
  • 1
    Vectors are implemented using arrays. Yeah, as a preset you should use arrays. Your question is too broad - wether you should use an array or a vector depends on what you're trying to do. – Ivan Rubinson Jun 29 '16 at 04:44
  • @IvanRubinson - I'm assuming you mean the vectors are a class that use an array? Its an array at its core? – JosephTLyons Jun 29 '16 at 04:48
  • Vectors were built on top of arrays (in many implementations) to deal with the *disadvantages* of manually allocating new space in fixed-size arrays. The only advantage to using arrays is lower overhead, which is mostly a problem with really weak computers (think like 10 years ago, or microcontrollers). – Aaron3468 Jun 29 '16 at 04:50
  • @T.C. - interesting. I'd like to hear more about this. I would think the fact it grows and shrinks dynamically in size might slow down applications that might need to use a loop to store a lot of information in a vector, but other than that, I'm totally unaware of what sort of issues come with vectors. – JosephTLyons Jun 29 '16 at 04:50
  • Possible duplicate of [Advantages of using arrays instead of std::vector?](http://stackoverflow.com/questions/4004015/advantages-of-using-arrays-instead-of-stdvector) – chema989 Jun 29 '16 at 05:02
  • Better possible duplicate: http://stackoverflow.com/a/6464658/310560 I think this answer is under-rated – Assimilater Jun 29 '16 at 05:57

4 Answers4

6

A std::vector manages a dynamic array. If your program need an array that changes its size dynamically at run-time then you would end up writing code to do all the things a std::vector does but probably much less efficiently.

What the std::vector does is wrap all that code up in a single class so that you don't need to keep writing the same code to do the same stuff over and over.

Accessing the data in a std::vector is no less efficient than accessing the data in a dynamic array because the std::vector functions are all trivial inline functions that the compiler optimizes away.

If, however, you need a fixed size then you can get slightly more efficient than a std::vector with a raw array. However you won't loose anything using a std::array in those cases.

The places I still use raw arrays are like when I need a temporary fixed-size buffer that isn't going to be passed around to other functions:

// some code

{ // new scope for temporary buffer

    char buffer[1024]; // buffer
    file.read(buffer, sizeof(buffer)); // use buffer

} // buffer is destroyed here

But I find it hard to justify ever using a raw dynamic array over a std::vector.

Galik
  • 47,303
  • 4
  • 80
  • 117
3

This is not a full answer, but one thing I can think of is, that the "ability to grow and shrink" is not such a good thing if you know what you want. For example: assume you want to save memory of 1000 objects, but the memory will be filled at a rate that will cause the vector to grow each time. The overhead you'll get from growing will be costly when you can simply define a fixed array

Generally speaking: if you will use an array over a vector - you will have more power at your hands, meaning no "background" function calls you don't actually need (resizing), no extra memory saved for things you don't use (size of vector...).

Additionally, using memory on the stack (array) is faster than heap (vector*) as shown here

*as shown here it's not entirely precise to say vectors reside on the heap, but they sure hold more memory on the heap than the array (that holds none on the heap)

Community
  • 1
  • 1
CIsForCookies
  • 12,097
  • 11
  • 59
  • 124
  • 1
    This totally makes sense, and I just made a comment about this up above. It would make sense to use an array to avoid it deleting and creating new memory locations, etc. – JosephTLyons Jun 29 '16 at 04:51
  • 3
    `std::vector` doesn't shrink automatically. If the upper limit on the size is known at compile time, you can also get away with only one allocation. –  Jun 29 '16 at 05:09
  • 2
    I don't see this as a real issue because the `resize` member function is available if you don't want to deal with resizing in a vector. So long as you don't use `push_back` or similar methods to increase the size after using `resize`, `vector` will not do any resizing. – Assimilater Jun 29 '16 at 05:11
  • @Assimilater you are right, but still, the point here is that array will cost less than some of the usually used vectors – CIsForCookies Jun 29 '16 at 05:17
2

One reason is that if you have a lot of really small structures, small fixed length arrays can be memory efficient.

compare

struct point
{
float coords[4]
}

with

struct point
{
std::vector<float> coords;
}

Alternatives include std::array for cases like this. Also std::vector implementations will over allocate, meaning that if you want resize to 4 slots, you might have memory allocated for 16 slots.

Furthermore, the memory locations will be scattered and hard to predict, killing performance - using an exceptionally larger number of std::vectors may also need to memory fragmentation issues, where new starts failing.

Mikhail
  • 7,749
  • 11
  • 62
  • 136
  • 1
    I'm not sure what you mean by the "locations will be scattered". `std::vector`, `std::array` and oldfashioned arrays are all contiguous, so not scattered. `&element[N] == &element[0] + N`. – MSalters Jun 29 '16 at 07:23
  • @MSalters so, if you have two std::vectors, they point to two different locations. Now imagine if you're describing a cloud of points, you're going to have millions of different points that in most cases are read sequentially. Yikes! – Mikhail Jun 30 '16 at 21:19
  • 1
    That's a bad design anyway, because a collection of points should be one vector of coordinate pairs, not a pair of vectors. – MSalters Jul 01 '16 at 07:21
  • @MSalters Though, ya vectors are guaranteed to be laid out contiguously, The idea he's getting at might be applicable to a N-Dimensional matrix naively implemented with vectors (though even then, I'm sure there's a "right" way to do it with allocators) – Assimilater Jul 01 '16 at 07:35
1

I think this question is best answered flipped around:

What advantages does std::vector have over raw arrays?

I think this list is more easily enumerable (not to say this list is comprehensive):

  • Automatic dynamic memory allocation
  • Proper stack, queue, and sort implementations attached
  • Integration with C++ 11 related syntactical features such as iterator

If you aren't using such features there's not any particular benefit to std::vector over a "raw array" (though, similarly, in most cases the downsides are negligible).

Despite me saying this, for typical user applications (i.e. running on windows/unix desktop platforms) std::vector or std::array is (probably) typically the preferred data structure because even if you don't need all these features everywhere, if you're already using std::vector anywhere else you may as well keep your data types consistent so your code is easier to maintain.

However, since at the core std::vector simply adds functionality on top of "raw arrays" I think it's important to understand how arrays work in order to be fully take advantage of std::vector or std::array (knowing when to use std::array being one example) so you can reduce the "carbon footprint" of std::vector.

Additionally, be aware that you are going to see raw arrays when working with

  • Embedded code
  • Kernel code
  • Signal processing code
  • Cache efficient matrix implementations
  • Code dealing with very large data sets
  • Any other code where performance really matters

The lesson shouldn't be to freak out and say "must std::vector all the things!" when you encounter this in the real world.

Also: THIS!!!!

  • One of the powerful features of C++ is that often you can write a class (or struct) that exactly models the memory layout required by a specific protocol, then aim a class-pointer at the memory you need to work with to conveniently interpret or assign values. For better or worse, many such protocols often embed small fixed sized arrays.
  • There's a decades-old hack for putting an array of 1 element (or even 0 if your compiler allows it as an extension) at the end of a struct/class, aiming a pointer to the struct type at some larger data area, and accessing array elements off the end of the struct based on prior knowledge of the memory availability and content (if reading before writing) - see What's the need of array with zero elements?
  • embedding arrays can localise memory access requirement, improving cache hits and therefore performance
Community
  • 1
  • 1
Assimilater
  • 944
  • 14
  • 33