यह C++ में एक वेक्टर से सबवेक्टर प्राप्त करने के लिए एक C++ प्रोग्राम है
एल्गोरिदम
कंस्ट्रक्टर के लिए वेक्टर की शुरुआत और अंत स्थिति को आरंभ करने के लिए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.
उदाहरण कोड
#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; }
आउटपुट
Sub vector is: 4 1 9 10