size() and resize() Functions in C++

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.

  1. /*
  2.  * C++ Program to demonstrate size() and resize() functions on vector
  3.  */
  4. #include <iostream>
  5. #include <vector>
  6. #include <iomanip>
  7. using namespace std;
  8.  
  9. void print(vector <int> vs)
  10. {   
  11.     vector <int>::iterator i;
  12.     cout << "Vector elements : ";
  13.     for(i = vs.begin(); i != vs.end(); i++)
  14.     {
  15.         cout << setw(2) << *i << "  ";
  16.     }
  17.     cout << endl;
  18. }
  19.  
  20. int main()
  21. {
  22.     int arr[] = {10, 20, 30, 40, 50};
  23.     int alen  = sizeof(arr) / sizeof(int);
  24.  
  25.     vector <int> vector(arr, arr + alen);
  26.     cout << "Vector of size = " << vector.size() << endl;
  27.     print(vector);
  28.     vector.resize(2 * alen);
  29.     cout << "Vector resized to size = " << vector.size() << endl;
  30.     vector.assign(10, 10);
  31.     print(vector);
  32. }

$ 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.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.