如何在 C++ 中向向量中追加一個向量?


透過 vector insert() 方法可以簡單地向一個向量中新增一個向量。

演算法

Begin
   Declare a function show().
      Pass a constructor of a vector as a parameter within show()
      function.
      for (auto const& i: input)
         Print the value of variable i.
   Declare vect1 of vector type.
      Initialize values in the vect1.
   Declare vect2 of vector type.
      Initialize values in the vect2.
   Call vect2.insert(vect2.begin(), vect1.begin(), vect1.end()) to
   append the vect1 into vect2.
   Print “Resultant vector is:”
   Call show() function to display the value of vect2.
End.

示例程式碼

 實際演示

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void show(vector<int> const &input) {
   for (auto const& i: input) {
      std::cout << i << " ";
   }
}
int main() {
   vector<int> v1 = { 1, 2, 3 };
   vector<int> v2 = { 4, 5 };
   v2.insert(v2.begin(), v1.begin(), v1.end());
   cout<<"Resultant vector is:"<<endl;
   show(v2);
   return 0;
}

輸出

Resultant vector is:
1 2 3 4 5

更新於: 2019 年 7 月 30 日

15K+ 瀏覽次數

啟動你的職業

透過完成課程獲得認證

開始學習
廣告