Yudop
Yudop

Reputation: 153

Should I define number of elements in a vector before or after knowing how many elements I'll use?

I'm trying to understand which way I should implement a vector so I can reduce my run time and memory usage in a program or it doesn't matter (depending solely of the computations my program does with those elements)?

Let's say I define a vector without knowing how many elements I'll use in my program but I know the max number of elements I'll be working with

#define MAX 10000
vector<int> eg(MAX);

In the other case I indicate first how many elements and then size it accordingly

vector<int> eg;
int n;
cin >> n;
eg.resize(n);

Upvotes: 2

Views: 357

Answers (2)

Steve H
Steve H

Reputation: 5529

Both. Because when you go to resize to the final number of elements, you will only be resizing to a lesser number of elements and that takes fewer cpu cycles than resizing to a greater number of elements (if you hadn't set MAX) because it doesn't have to copy elements to different locations if there isn't room in the current contiguous location.

Upvotes: 0

Vlad from Moscow
Vlad from Moscow

Reputation: 311058

If you know the maximum number of elements that the vector will store then it is better to use member function reserve. For example

const std::vector<int>::size_type MAX = 10000;
vector<int> eg;
eg.reserve( MAX );

Upvotes: 2

Related Questions