Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to join two Vectors using STL in C++?
In this tutorial, we will be discussing a program to understand how to join two given vectors using STL library in C++.
To join two given vectors we would be using the set_union() method from the STL library.
Example
#include <bits/stdc++.h>
using namespace std;
int main(){
//collecting the vectors
vector<int> vector1 = { 1, 45, 54, 71, 76, 12 };
vector<int> vector2 = { 1, 7, 5, 4, 6, 12 };
sort(vector1.begin(), vector1.end());
sort(vector2.begin(), vector2.end());
cout << "First Vector: ";
for (int i = 0; i < vector1.size(); i++)
cout << vector1[i] << " ";
cout << endl;
cout << "Second Vector: ";
for (int i = 0; i < vector2.size(); i++)
cout << vector2[i] << " ";
cout << endl;
vector<int> v(vector1.size() + vector2.size());
vector<int>::iterator it, st;
it = set_union(vector1.begin(),vector1.end(),vector2.begin(), vector2.end(), v.begin());
cout << "\nAfter joining:\n";
for (st = v.begin(); st != it; ++st)
cout << *st << ", ";
cout << '\n';
return 0;
}
Output
First Vector: 1 12 45 54 71 76 Second Vector: 1 4 5 6 7 12 After joining: 1, 4, 5, 6, 7, 12, 45, 54, 71, 76,
Advertisements