This C++ program demonstrates size() and resize() functions on a vector. The function size() returns the size of the container and the function resize() resizes the container to the specified size and moves the elements to the new allocated space.
Here is the source code of the C++ program which demonstrates size() and resize() functions on a vector. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.
/*
* C++ Program to demonstrate size() and resize() functions on vector
*/
#include <iostream>
#include <vector>
#include <iomanip>
using namespace std;
void print(vector <int> vs)
{
vector <int>::iterator i;
cout << "Vector elements : ";
for(i = vs.begin(); i != vs.end(); i++)
{
cout << setw(2) << *i << " ";
}
cout << endl;
}
int main()
{
int arr[] = {10, 20, 30, 40, 50};
int alen = sizeof(arr) / sizeof(int);
vector <int> vector(arr, arr + alen);
cout << "Vector of size = " << vector.size() << endl;
print(vector);
vector.resize(2 * alen);
cout << "Vector resized to size = " << vector.size() << endl;
vector.assign(10, 10);
print(vector);
}
$ a.out Vector of size = 5 Vector elements : 10 20 30 40 50 Vector resized to size = 10 Vector elements : 10 10 10 10 10 10 10 10 10 10
Sanfoundry Global Education & Learning Series – 1000 C++ Programs.
advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.
Next Steps:
- Get Free Certificate of Merit in C++ Programming
- Participate in C++ Programming Certification Contest
- Become a Top Ranker in C++ Programming
- Take C++ Programming Tests
- Chapterwise Practice Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Chapterwise Mock Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Related Posts:
- Apply for Information Technology Internship
- Buy Programming Books
- Buy C++ Books
- Practice Programming MCQs
- Buy Computer Science Books