C++のベクトルからサブベクトルを取得する
これは、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
-
C++でのvector::resize()とvector ::reserved()
ベクトルには、要素が挿入または削除されたときに動的配列のように自動的にサイズを変更する機能があり、コンテナはストレージを自動的に処理します。 vector resize()とvector reserved()の主な違いは、resize()がベクトルのサイズを変更するために使用されることです。reserve()は使用されません。reserve()は、少なくとも指定された要素の数を格納するためにのみ使用されます。メモリを再割り当てする必要はありません。ただし、resize()では、数値が現在の数値よりも小さい場合、メモリのサイズが変更され、その上の余分なスペースが削除されます。 vector
-
C++での型推論
型推論または推論とは、プログラミング言語での式のデータ型の自動検出を指します。これは、いくつかの強く静的に型付けされた言語に存在する機能です。 C ++では、autoキーワード(C ++ 11で追加)が自動型推定に使用されます。たとえば、ベクトルを反復処理するイテレータを作成する場合、その目的でautoを使用するだけです。 例 #include<iostream> #include<vector> using namespace std; int main() { vector<int> arr(10);