이것은 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