Home » C++ STL

vector::shrink_to_fit() function with example in C++ STL

C++ STL vector::shrink_to_fit() function: Here, we are going to learn about the shrink_to_fit() function of vector header in C++ STL with example.
Submitted by Radib Kar, on May 17, 2019

C++ vector::shrink_to_fit() function

vector::shrink_to_fit() is a library function of "vector" header, which is used to reduce capacity to fit size. Refer to example to understand in details.

This may lead to reallocation, but elements don't alter.

Note: To use vector, include <vector> header.

Syntax of vector::shrink_to_fit() function

    vector::shrink_to_fit();

Parameter(s): none – It accepts nothing.

Return value: void – It returns nothing.

Example:

    Input:
    //capacity is initialized to be 100
    vector<int> arr(50); 
    arr.capacity() =50
    
    Resize:
    //doesn't change capacity though
    arr.resize(10); 
    arr.capacity() =50
    
    shrink_to_fit:
    //changes capacity as per resize, 
    //thus this practically reduced the capacity
    arr.shrink_to_fit();
    arr.capacity() =10

C++ program to demonstrate example of vector::shrink_to_fit() function

#include <iostream>
#include <vector>
using namespace std;

int main()
{
    vector<int> arr(50); //capacity is initialized to be 100
    cout << "...capacity of the vector: " << arr.capacity() << "...\n";

    arr.resize(10); //doesn't change capacity though
    cout << "...After resizing...\n";
    cout << "capacity of the vector: " << arr.capacity() << "\n";

    arr.shrink_to_fit(); //changes capacity as per resized vector
    cout << "...After using shrink_to_fit...\n";
    cout << "capacity of the vector: " << arr.capacity() << "\n";

    return 0;
}

Output

...capacity of the vector: 50... 
...After resizing... 
capacity of the vector: 50 
...After using shrink_to_fit...
capacity of the vector: 10 

Reference: C++ vector::shrink_to_fit()






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.