• 15
• 15
• 11
• 9
• 10

# std::vector

This topic is 4955 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

When using the standard vector class is it faster to use push_back() to add elements or faster to allocate x memory spaces (double the vector size for example). This is for use when quite a few elements need to be added and it needs to be done as fast as possible Thanks in advance

##### Share on other sites
You can use reserve() before push_back() to speed things up. reserve() will actually reserve all the memory ahead of time so the vector doesn't have to keep reallocating.

##### Share on other sites
Note that if you are going to keep the vector for some time the memory used by the vector will not be released even if you pop all the elements.

##### Share on other sites
With std::vector does indexing go from 0->size-1 or from 1->size or from 0->size?

eg:
std::vector<int> x(10);

int size = x.size();

-> size = 10

x[0] = 1; // Seems OK
x[1] = 2; // Seems OK
x[10] = 11; // Seems OK

However, size was 10 and now 11 slots "seem" to be available. Is this correct or would one of these operations result in indexing unallocated memory? Just because with standard C the indexing would normally only be in the range 0->size-1 so I'm a bit confused??

##### Share on other sites
The indexing is zero-based.
std::vector<int> x(10);
creates a vector with ten elements, and the default constructor will be used for each.
This means you can use indices 0 through 9.
10 may work because the vector reserves more space than it actually uses - but it would be incorrect try to access the 11th element.
size() returns the actually size of the vector. capacity() will return the amount of space reserved, which is greater than or equal to its size.