vector

hi,
I'm using vector instead of array.

[int data[N];]

is replaced by:

[vector <int> data(N);]

so, my question is I have to add this line also or not?

# include <vector>

Thanks
The short answer? Yes.
If you do use "vector" in a way that the compiler has to know what the "vector" actually is, then yes, inclusion of its definition is necessary.
1
2
3
4
5
#include <vector>
...
std::vector<int> data; // no size limit
data.push_back(2); // Add number to back of array
cout << data[0];

...
int data[N]; // size limit of N
data[index++] = 2; // Add number to back of array (index must be < N)
cout << data[0];
Last edited on
You can create a vector the way that the OP was suggesting, however.

std::vector can have following constructor:
explicit vector (size_type n);
which initializes the size of the vector to that size.

Yes, that can make a difference (especially for loading lots of data into a vector), due to memory allocation taking a lot of the computer's resources.

Also, @Stewbond, your example has std::cout << data[2], which is outside the range of the vector. Therefore, the result is undefined.
Last edited on
That constructor reserves space to save memory allocation time, but data.size() will still return 0 until data.push_back() is used. Just thought I should make that clear.

You cannot
1
2
3
std::vector<int> data(N); 
data[N-1] = 0; 
cout << data[N-1];
> std::vector can have following constructor:
> explicit vector (size_type n);
> which initializes the size of the vector to that size.

Yes, +1


> That constructor reserves space to save memory allocation time, but data.size() will still return 0

No.
Last edited on
Topic archived. No new replies allowed.