vector assign() in C++

assign(): It assigns the given value to the vector.

Parameters:

n: number of elements to be assigned.

Val: Value to be assigned

Syntax: vecName.assign(n,Val)

This function basically fills the vector with n copies of the given value.

The size of the resulting vector is the same as the number of elements to be assigned

File: stl_vector.h

For Example :

vec.assign(4,1) => vec = {1, 1, 1, 1}

Example:

Output: 1 1 1 1

Approach

C++

#include <bits/stdc++.h>
using namespace std;

int main()
{
    vector<intvec;

    //here we assigns 4 copies of 1
    //into the vector
    vec.assign(41);

    //print the vector
    for (int i = 0i < vec.size(); i++)
        cout << vec[i] << " ";

    return 0;
}


No comments:

Post a Comment