i'm just a beginner in c++ . In my program i use vector push_back and go through this process many times .i also print the vector capacity after using push_back. the output shows that the capacity of the vector increases directly from 2 to 4 and then from 4 to 8. is this the way it works or is the capacity suppose to increase by 1 each time. I had this doubt because in 1 of the tutorials i was viewing the authors output showed the capacity of the vector increasing by one rather than powers of 2.
#include<iostream>
#include<vector>
void printStack(const std::vector<int> &stack)
{
for (const auto &element : stack)
std::cout << element << ' ';
std::cout << "(cap " << stack.capacity() << " size " << stack.size() << ")\n";
}
int main()
{
std::vector<int> stack;
printStack(stack);
stack.push_back(5); // push_back() pushes an element on the stack
printStack(stack);
stack.push_back(3);
printStack(stack);
stack.push_back(2);
printStack(stack);
printStack(stack);
stack.push_back(5); // push_back() pushes an element on the stack
printStack(stack);
stack.push_back(3);
printStack(stack);
stack.push_back(2);
printStack(stack);
return 0;
}
Output:- (cap 0 size 0)
5 (cap 1 size 1)
5 3 (cap 2 size 2)
5 3 2 (cap 4 size 3)
5 3 2 (cap 4 size 3)
5 3 2 5 (cap 4 size 4)
5 3 2 5 3 (cap 8 size 5)
5 3 2 5 3 2 (cap 8 size 6)
Thanks in advance.