Computer >> Máy Tính >  >> Lập trình >> C ++

chức năng chèn vectơ () trong C ++ STL

Hàm vector insert () trong C ++ STL giúp tăng kích thước của vùng chứa bằng cách chèn các phần tử mới vào trước các phần tử ở vị trí được chỉ định.

Đây là một hàm được xác định trước trong C ++ STL.

Chúng tôi có thể chèn các giá trị bằng ba loại cú pháp

1. Chèn giá trị bằng cách chỉ đề cập đến vị trí và giá trị:

vector_name.insert(pos,value);

2. Chèn các giá trị bằng cách đề cập đến vị trí, giá trị và kích thước:

vector_name.insert(pos,size,value);

3. Chèn các giá trị trong một vectơ trống khác tạo thành một vectơ đã điền bằng cách đề cập đến vị trí, nơi các giá trị sẽ được chèn và các trình vòng lặp của vectơ đã điền:

empty_eector_name.insert(pos,iterator1,iterator2);

Thuật toán

Begin
   Declare a vector v with values.
   Declare another empty vector v1.
   Declare another vector iter as iterator.
   Insert a value in v vector before the beginning.
   Insert another value with mentioning its size before the beginning.
   Print the values of v vector.
   Insert all values of v vector in v1 vector with mentioning the iterator of v vector.
   Print the values of v1 vector.
End.

Ví dụ

#include<iostream>
#include <bits/stdc++.h>
using namespace std;

int main() {
   vector<int> v = { 50,60,70,80,90},v1;        //declaring v(with values), v1 as vector.
   vector<int>::iterator iter;                  //declaring an iterator
   iter = v.insert(v.begin(), 40);              //inserting a value in v vector before the beginning.
   iter = v.insert(v.begin(), 1, 30);           //inserting a value with its size in v vector before the beginning.
   cout << "The vector1 elements are: \n";
   for (iter = v.begin(); iter != v.end(); ++iter)
      cout << *iter << " "<<endl;             // printing the values of v vector
   v1.insert(v1.begin(), v.begin(), v.end()); //inserting all values of v in v1 vector.
   cout << "The vector2 elements are: \n";
   for (iter = v1.begin(); iter != v1.end(); ++iter)
      cout << *iter << " "<<endl;            // printing the values of v1 vector
   return 0;
}

Đầu ra

The vector1 elements are:
30
40
50
60
70
80
90
The vector2 elements are:
30
40
50
60
70
80
90