How push_back() increase size and capacity of a vector in C++

2 Answers

0 votes
#include <iostream>
#include <vector>
#include <algorithm>

using std::cout;
using std::endl;
using std::vector;

int main()
{
	vector<char> vec(10);

	cout << "size: " << vec.size() << endl;
	cout << "capacity: " << vec.capacity() << endl;

	vec.push_back('z');

	cout << endl << "push_back" << endl << endl;

	cout << "size: " << vec.size() << endl;
	cout << "capacity: " << vec.capacity() << endl;
	
	return 0;
}

/*
run:

size: 10
capacity: 10

push_back

size: 11
capacity: 15

*/

 



answered May 2, 2018 by avibootz
0 votes
#include <iostream>
#include <vector>
#include <algorithm>

using std::cout;
using std::endl;
using std::vector;

int main()
{
	vector<char> vec(10);

	vec.resize(100);

	cout << "size: " << vec.size() << endl;
	cout << "capacity: " << vec.capacity() << endl;

	vec.push_back('z');

	cout << endl << "push_back" << endl << endl;

	cout << "size: " << vec.size() << endl;
	cout << "capacity: " << vec.capacity() << endl;
	
	return 0;
}

/*
run:

size: 100
capacity: 100

push_back

size: 101
capacity: 150

*/

 



answered May 2, 2018 by avibootz

Related questions

1 answer 274 views
2 answers 374 views
1 answer 335 views
1 answer 190 views
190 views asked Mar 13, 2025 by avibootz
1 answer 258 views
1 answer 347 views
1 answer 234 views
...