×

C++ STL Tutorial

C++ STL Algorithm

C++ STL Arrays

C++ STL String

C++ STL List

C++ STL Stack

C++ STL Set

C++ STL Queue

C++ STL Vector

C++ STL Map

C++ STL Multimap

C++ STL MISC.

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

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

C++ vector::resize() function

vector::resize() is a library function of "vector" header, it is used to resize the vector, it accepts the updated number of elements and a default value (optional) and resizes the vector container.

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

Syntax

Syntax of vector::resize() function

vector::resize();

Parameter(s)

n – is the updated size, val – is the default value to be assigned to the new size, and value_type() – it is the value type of the container (a reference of the type of the first template parameter).

Return value

void – It returns nothing.

Sample Input and Output

Input:
vector<int> vector1{ 1, 2, 3, 4, 5 };

Function call:
cout << vector1.resize(10);

Output:
//if we print elements
1 2 3 4 5 0 0 0 0 0

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

//C++ STL program to demonstrate example of
//vector::resize() function

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

int main()
{
    vector<int> v1;

    //printing the size of the vector
    cout << "Total number of elements: " << v1.size() << endl;

    //pushing elements
    v1.push_back(10);
    v1.push_back(20);
    v1.push_back(30);
    v1.push_back(40);
    v1.push_back(50);

    //printing the size of the vector
    cout << "Total number of elements: " << v1.size() << endl;

    //printing the elements
    cout << "vector elements are: ";
    for (int x : v1)
        cout << x << " ";
    cout << endl;

    //resizing the size with default value
    //and printing the elements
    v1.resize(8, 99);

    //printing the size of the vector
    cout << "Total number of elements: " << v1.size() << endl;

    //printing the elements
    cout << "vector elements are: ";
    for (int x : v1)
        cout << x << " ";
    cout << endl;

    //resizing the size without default value
    //and printing the elements
    v1.resize(10);

    //printing the size of the vector
    cout << "Total number of elements: " << v1.size() << endl;

    //printing the elements
    cout << "vector elements are: ";
    for (int x : v1)
        cout << x << " ";
    cout << endl;

    return 0;
}

Output

Total number of elements: 0
Total number of elements: 5
vector elements are: 10 20 30 40 50
Total number of elements: 8
vector elements are: 10 20 30 40 50 99 99 99
Total number of elements: 10
vector elements are: 10 20 30 40 50 99 99 99 0 0

Reference: C++ vector::resize()

Related Tutorials

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.