📜  如何在C++中使用STL连接两个Vector?

📅  最后修改于: 2021-05-30 08:06:26             🧑  作者: Mango

给定两个向量,请在C++中使用STL将这两个向量连接起来。

例子:

方法:可以借助STL中提供的set_union()函数来完成连接。

句法:

set_union (InputIterator1 first1, InputIterator1 last1,
           InputIterator2 first2, InputIterator2 last2,
           OutputIterator result);
// C++ program to join two Vectors
// using set_union() in STL
  
#include 
using namespace std;
  
int main()
{
    // Get the vector
    vector vector1 = { 1, 45, 54, 71, 76, 12 };
    vector vector2 = { 1, 7, 5, 4, 6, 12 };
  
    // Sort the vector
    sort(vector1.begin(), vector1.end());
    sort(vector2.begin(), vector2.end());
  
    // Print the vector
    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;
  
    // Initialise a vector
    // to store the common values
    // and an iterator
    // to traverse this vector
    vector v(vector1.size() + vector2.size());
    vector::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;
}
输出:
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,
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”