Appending a vector to a vector in C++ STL

C++ STL | appending a vector to a vector: Here, we are going to learn how can we append a vector to another vector in C++ STL program?
Submitted by IncludeHelp, on May 17, 2019

Given two vectors and we have to append one vector's all elements at the end of another vector.

Appending a vector elements to another vector

To insert/append a vector's elements to another vector, we use vector::insert() function.

Read mode: C++ STL vector::insert() function

Syntax:

//inserting elements from other containers 
vector::insert(iterator position, iterator start_position, iterator end_position);

Parameter(s): iterator position, iterator start_position, iterator end_positioniterator position is the index using iterator of the vector where elements to be added, start_position, iterator end_position are the iterators of another container whose value will be inserted in the current vector.

Return value: void – It returns nothing..

Example:

    Input:
    vector<int> v1{ 10, 20, 30, 40, 50 };
    vector<int> v2{ 100, 200, 300, 400 };

    //appending elements of vector v2 to vector v1
    v1.insert(v1.end(), v2.begin(), v2.end());

    Output:
    v1: 10 20 30 40 50 100 200 300 400
    v2: 100 200 300 400

C++ STL program to append a vector to a vector

//C++ STL program to append a vector to a vector
#include <iostream>
#include <vector>
using namespace std;

int main()
{
    //vector declaration
    vector<int> v1{ 10, 20, 30, 40, 50 };
    vector<int> v2{ 100, 200, 300, 400 };

    //printing elements
    cout << "before appending..." << endl;
    cout << "size of v1: " << v1.size() << endl;
    cout << "v1: ";
    for (int x : v1)
        cout << x << " ";
    cout << endl;

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

    //appending elements of vector v2 to vector v1
    v1.insert(v1.end(), v2.begin(), v2.end());

    cout << "after appending..." << endl;
    cout << "size of v1: " << v1.size() << endl;
    cout << "v1: ";
    for (int x : v1)
        cout << x << " ";
    cout << endl;

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

    return 0;
}

Output

before appending...
size of v1: 5
v1: 10 20 30 40 50
size of v2: 4
v2: 100 200 300 400
after appending...
size of v1: 9
v1: 10 20 30 40 50 100 200 300 400
size of v2: 4
v2: 100 200 300 400

Related Tutorials



Comments and Discussions!

Load comments ↻





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