How to join two vectors in C++ STL?

C++ STL | joining two vectors: Here, we are going to learn how to join two vectors in C++ STL?
Submitted by IncludeHelp, on May 21, 2019

Given two vectors and we have to join them using C++ STL program.

Joining two vectors

To join two vectors, we can use set_union() function, it accepts the iterators of both vectors pointing to the starting and ending ranges and an iterator of result vector (in which we stores the result) pointing to the starting position and returns an iterator pointing to the end of the constructed range.

Note: To use vector – include <vector> header, and to use set_union() function – include <algorithm> header or we can simply use <bits/stdc++.h> header file.

Syntax:

    std::set_union(
        iterator start1, iterator end1, 
        iterator start1, iterator end1, 
        iterator start3);

Here, iterator start1, iterator end1 – are the iterators pointing to the starting and ending position of first vector, iterator start2, iterator end2 – are the iterators pointing to the starting and ending position of second vector, and iterator start3 – is an iterator pointing to the starting position of the result vector.

C++ STL program to join two vectors

//C++ STL program to join two vectors
#include <bits/stdc++.h>
using namespace std;

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

    //sorting the vectors
    sort(v1.begin(), v1.end());
    sort(v2.begin(), v2.end());

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

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

    //declaring result vector to
    //store the joined elements
    vector<int> v3(v1.size() + v2.size());

    //iterator to store return type
    vector<int>::iterator it, end;

    end = set_union(
        v1.begin(), v1.end(),
        v2.begin(), v2.end(),
        v3.begin());

    cout << "After joining v3: ";
    for (it = v3.begin(); it != end; it++)
        cout << *it << " ";
    cout << endl;

    return 0;
}

Output

v1: 10 10 20 20 30 40 50
v2: 10 20 30 50 100 200
After joining v3: 10 10 20 20 30 40 50 100 200

Related Tutorials




Comments and Discussions!

Load comments ↻






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