arrays versus vectors

In C++ Why would you use arrays at all when vectors can do the same and has more features, like v.size(), or grow or shrinking, etc.?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <vector>
using namespace std;


int main(){
    int array[] = {1,2,3};
    vector<int> v;
    
    for (int i=1; i<4; i++){
        v.push_back(i);
    }
    for (int i=0; i<sizeof(array)/sizeof(array[0]); i++){
        cout << array[i] << ' ';
    }
    cout << '\n';
    for (int i=0; i<v.size(); i++){
        cout << v[i] << ' ';
    }
}


I mean at this point the vector and array contain the same values and number of values, but the vector can be added to or deleted from. IF you started using arrays, and then decided you need to dynamically change the size, you would have to convert it to vector anyways, so why waste time setting it originally to arrays?
Last edited on
metulburr wrote:
In C++ Why would you use arrays at all when vectors can do the same and has more features, like v.size(), or grow or shrinking, etc.?

Depends on what you're doing. Sometimes you just need the base functionality of an array and don't care about the other features. But most of the time using C++ you'll be better off using a vector.
Why would you use arrays at all when vectors can do the same and has more features

Occasionally you may want to allocate your data on stack (std::vector puts them wherever the allocator tells it to, but do you have a stack allocator at hand?) or you may wish to statically initialize your data before any dynamic initialization takes place.
It's pretty rare indeed, and std::array works better for those cases anyway.
Topic archived. No new replies allowed.