2

Possible Duplicate:
C++ STL vector vs array in the real world

To start of I have a little below average knowledge of C++ and advanced knowledge of C
Many times, I want to ask something code related and include or refer to some code and an array comes up everyone instantly lock on this aspect and suggest I should instead use a vector, even if it doesn't have to do anything related to my problem.

The problem is that this is the way I learned how to use C++, obviously something I inherited from learning plain C first, and I am quite used to it, although I feel confident about using vectors also, I just prefer arrays over vectors.

My questions are why should someone use a vector instead of an array, what does he earn by doing so, even if he is quite used to arrays?
Also if arrays are not preferred over vectors why doesn't everyone simply use vectors for everything?

Community
  • 1
  • 1
Theocharis K.
  • 1,281
  • 1
  • 16
  • 43
  • 4
    The question is why would anyone prefer _arrays_ over _vectors_, and handling all the details themselves... – K-ballo Jan 11 '13 at 00:12
  • 1
    The real distinction is between *dynamically allocated* arrays and vectors, of course. Fixed-size arrays are perfectly fine, though you should use `std::array` for those. – Kerrek SB Jan 11 '13 at 00:18
  • @KerrekSB: The distinction is between _automatically-allocated_ arrays and vectors, of course. Dynamically-allocated arrays _are_ vectors, at some level of abstraction. – Lightness Races in Orbit Jan 11 '13 at 00:20

4 Answers4

5

Vectors have a dimension that may be provided at run-time, such as a user-provided value or something derived from a file's contents.

The size of an array, by contrast, must be hard-coded into your program. It is fixed.

why doesn't everyone simply use vectors for everything?

There is a run-time performance cost for using vectors over arrays when you don't need to. Personally I've never written code in which this is a bottleneck and therefore rarely use raw arrays; still, such scenarios do exist.


The exception is when you create a block of memory (an "array" in some sense) dynamically with new[]; this is the exact language feature that is encapsulated by std::vector.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
  • But using `new` on an array can make dynamically allocated arrays or am I wrong somewhere? – Theocharis K. Jan 11 '13 at 00:16
  • @Aposperite: Sure. `std::vector` is a wrapper around that process so the same logic applies in that case. (Strictly speaking you don't create an "array" in that case but a "block of memory", but on neither an abstract nor a practical level can I defend the difference.) – Lightness Races in Orbit Jan 11 '13 at 00:18
  • So in general there is no practical difference between `dynamically allocated arrays` and `vectors` other than the fact you can presumably handle vectors easier and more bug-free than arrays? – Theocharis K. Jan 11 '13 at 00:25
  • 1
    @Aposperite: Sort of. More or less. Less because `std::vector` is an object wrapper and, as such, you can just pass it around with worrying about ownership. If you try to handle a pointer-to-a-dynamically-allocated-array yourself then you get into a pickle pretty easily. Also a `std::vector` object will handle _all_ the hard work for you, such as resizing the array if you need. – Lightness Races in Orbit Jan 11 '13 at 00:26
  • Not sure if you are talking about the `new T[n]` case or the `std::vector` case, but `new T[n]` definitely *does* create an array. See the last sentence of 5.3.4 §1, for example: " If it is an array, the new-expression returns a pointer to the initial element of the array." – fredoverflow Jan 11 '13 at 11:23
0

One of the reasons is the performance behavior of each container, as explained here:

Many containers have several member functions in common, and share functionalities. The decision of which type of container to use for a specific need does not generally depend only on the functionality offered by the container, but also on the efficiency of some of its members (complexity). This is especially true for sequence containers, which offer different trade-offs in complexity between inserting/removing elements and accessing them.

sinelaw
  • 16,205
  • 3
  • 49
  • 80
0

Vectors

  • do their own allocation and deallocation of memory
  • resize automatically when expanding
  • can be used where STL containers can, which includes many many algorithms and methods
  • have many other methods that are useful

Arrays

  • take less memory overall
  • Are used in C code, so are used for reverse compatibility
djechlin
  • 59,258
  • 35
  • 162
  • 290
  • Vectors can be used in a compatible fashion with _C_ apis as well, I don't think that last point holds... – K-ballo Jan 11 '13 at 00:13
  • I don't buy the compatibility argument. If you're interfacing with C code, you can provide a pointer to `std::vector` data precisely as easily as you can to array data. – Lightness Races in Orbit Jan 11 '13 at 00:13
  • Also if I am not mistaken `vectors` are a *bit* slower than `arrays` and this could be a problem in big programs. Right? Or this is another myth too? – Theocharis K. Jan 11 '13 at 00:34
  • @Aposperite: That's a myth, to a degree. There is a tiny amount of overhead when the vector is created, but even in "big programs" you should be coding in such a way that this makes zero difference i.e. not creating a vector (_or_ an array!) in a tight loop. No difference in other usage. – Lightness Races in Orbit Jan 11 '13 at 15:40
0

The main reason is that the size of a std::vector can be decided at run time and is resizeable. The vector also supports iterators, which means it works well with many stl algorithms such as std::for_each or std::anyof. Vectors can also be used to allocate memory in a safe way and that is compatible with C functions.

If you are using the Windows API, std::vector is very useful with the get-size-get-data paradigm that is used in many functions. This is where you typically call the same function twice, the first time to get the data size, the second time to actually read the data. For example:

DWORD size = 0;
DWORD type = 0;
if ( RegQueryValueEx( HKEY_LOCAL_MACHINE, 
    L"SOFTWARE\\Microsoft\\.NETFramework\\InstallRoot", 
    nullptr, 
    &type, 
    nullptr, 
    &size ) == ERROR_SUCCESS )
{
    std::vector<BYTE> data( size );
    if ( RegQueryValueEx( HKEY_LOCAL_MACHINE, 
        L"SOFTWARE\\Microsoft\\.NETFramework\\InstallRoot", 
        nullptr, 
        &type, 
        &data[0], 
        &size ) == ERROR_SUCCESS )
    {
      //We have read the data
    }
}

The size of an array is decided at compile-time and cannot be resized. Arrays are still used in C.

Steve
  • 7,171
  • 2
  • 30
  • 52