这是一个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 “子向量是:” . 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<<"子向量是:"<<endl;
vector<int> sub_vector = s(v, a, b);
show(sub_vector);
return 0;
}输出结果
子向量是: 4 1 9 10