×

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::assign() function with example in C++ STL

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

C++ vector::assign() function

vector::assign() is a library function of "vector" header, it is used to initialize a vector or assign content to a vector, it assigns the new content to the vector, update the existing content, and also resizes the vector's size according to the content.

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

Syntax

Syntax of vector::assign() function

vector::assign(iterator_first, iterator_last);
vector::assign(size_type n, value_type value);

Parameter(s)

In case of type 1: iterator_first, iterator_last – are the first and last iterators of a sequence with them we are going to assign the vector.
In case of type 2: n – is the size of the vector and value – is a constant value to be assigned.

Return value

void – In both of the cases it returns nothing.

Sample Input and Output

Input:
vector<int> v1;
vector<int> v2;
    
//assigning
v1.assign(5, 100);
v2.assign(v1.begin(), v1.end());

Output:
//if we print the value
v1: 100 100 100 100 100
v2: 100 100 100 100 100

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

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

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

int main()
{
    //declaring vectors
    vector<int> v1;
    vector<int> v2;
    vector<int> v3;

    //an array that will be used to assign a vector
    int arr[] = { 10, 20, 30, 40, 50 };

    //assigning vectors
    //assigning v1 with 5 elements and 100 as default value
    v1.assign(5, 100);

    //assigning v1 with array
    v2.assign(arr + 0, arr + 5);

    //assigning v3 with vector v2
    v3.assign(v2.begin(), v2.end());

    //pritning the vectors
    cout << "v1: ";
    for (int x : v1)
        cout << x << " ";
    cout << endl;

    cout << "v2: ";
    for (int x : v2)
        cout << x << " ";
    cout << endl;

    cout << "v3: ";
    for (int x : v3)
        cout << x << " ";
    cout << endl;

    return 0;
}

Output

v1: 100 100 100 100 100
v2: 10 20 30 40 50
v3: 10 20 30 40 50

Reference: C++ vector::assign()

Related Tutorials

Comments and Discussions!

Load comments ↻





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