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

Lấy một chương trình con từ một vectơ trong C ++

Đây là một chương trình C ++ để lấy một trình con từ một vectơ trong C ++

Thuật toán

Begin
  Declare s as vector s(vector const &v, int m, int n) to
   initialize start and end position of vector to constructor.
      auto first = v.begin() + m.  
      auto last = v.begin() + n + 1.
      Declare a variable vector of vector type.
         Pass the value of first and last position of vector.
      Return vector.
   Declare a template T.
   Declare a function show().
      Pass constructor of vector v as parameter.
      for (auto i: v)
         print the value of variable i.
   Declare a vector v.
      Initiation values in v vector.
      Initialize two variables a = 3, b = 6.
      Print “Sub vector is:” .
      Declare another vector sub_vector.
         vector sub_vector = s(v, a, b) to initialize values to the
         sub vector by mentioning the start and end position of
         vector v.
   call show() function to display the values of sub_vector.
End.

Mã mẫu

#include <iostream>
#include <vector>
using namespace std;
template<typename T>
vector<T> s(vector<T> const &v, int m, int n) {
   auto first = v.begin() + m;
   auto last = v.begin() + n + 1;
   vector<T> vector(first, last);
   return vector;
}
template<typename T>
void show(vector<T> const &v) {
   for (auto i: v) {
      cout << i << ' ';
   }
   cout << '\n';
}
int main() {
   vector<int> v = {7,6,2,4,1 ,9,10,15,17};
   int a = 3, b = 6;
   cout<<"Sub vector is:"<<endl;
   vector<int> sub_vector = s(v, a, b);
   show(sub_vector);
   return 0;
}

Đầu ra

Sub vector is:
4 1 9 10