STL SetC++プログラムでの挿入と削除
このチュートリアルでは、C++で設定されたSTLの挿入と削除を理解するためのプログラムについて説明します。
セットはコンテナ要素です。一意にするためのプロパティは、一意の要素のみを含めることができ、並べ替えられた方法でループできることです。
挿入
#include<iostream>
#include<set>
using namespace std;
int main(){
set<int> st;
//declaring iterators
set<int>::iterator it = st.begin();
set<int>::iterator it1, it2;
pair< set<int>::iterator,bool> ptr;
//inserting a single element
ptr = st.insert(20);
if (ptr.second)
cout << "The element was newly inserted" ;
else cout << "The element was already present" ;
cout << "\nThe set elements after 1st insertion are : ";
for (it1 = st.begin(); it1!=st.end(); ++it1)
cout << *it1 << " ";
st.insert(it, 24);
cout << "\nThe set elements after 2nd insertion are : ";
for (it1 = st.begin(); it1!=st.end(); ++it1)
cout << *it1 << " ";
int arr[3] = { 25, 24, 26 };
st.insert(arr, arr+3);
cout << "\nThe set elements after 3rd insertion are : ";
for (it1 = st.begin(); it1!=st.end(); ++it1)
cout << *it1 << " ";
} 出力
The element was newly inserted The set elements after 1st insertion are : 20 The set elements after 2nd insertion are : 20 24 The set elements after 3rd insertion are : 20 24 25 26
削除
#include<iostream>
#include<set>
using namespace std;
int main(){
set<int> st;
//declaring iterators
set<int>::iterator it;
set<int>::iterator it1;
set<int>::iterator it2;
pair< set<int>::iterator,bool> ptr;
//inserting values in set
for (int i=1; i<10; i++)
st.insert(i*5);
cout << "The set elements after insertion are : ";
for (it1 = st.begin(); it1!=st.end(); ++it1)
cout << *it1 << " ";
it = st.begin();
cout << endl;
++it;
st.erase(it);
//printing set elements after deletion
cout << "The set elements after 1st deletion are : ";
for (it1 = st.begin(); it1!=st.end(); ++it1)
cout << *it1 << " ";
st.erase(40);
cout << "\nThe set elements after 2nd deletion are : ";
for (it1 = st.begin(); it1!=st.end(); ++it1)
cout << *it1 << " ";
++it;
++it;
++it;
++it;
st.erase(it, st.end());
cout << "\nThe set elements after 3rd deletion are : ";
for (it1 = st.begin(); it1!=st.end(); ++it1)
cout << *it1 << " ";
cout << endl;
} 出力
The set elements after insertion are : 5 10 15 20 25 30 35 40 45 The set elements after 1st deletion are : 5 15 20 25 30 35 40 45 The set elements after 2nd deletion are : 5 15 20 25 30 35 45 The set elements after 3rd deletion are : 5 15 20
-
STLにSet_Intersectionを実装するC++プログラム
2つのセットの共通部分は、両方のセットに共通する要素によってのみ形成されます。関数によってコピーされる要素は、常に同じ順序で最初のセットから取得されます。両方のセットの要素はすでに注文されている必要があります。 一般的な集合演算は-です セットユニオン 交差点を設定 対称集合の差または排他的論理和 差または減算を設定 アルゴリズム Begin Declare set vector v and iterator st. Initialize st = set_intersection (set1, set1 + n, set2, s
-
STLにSet_Differenceを実装するC++プログラム
2つのセットの違いは、2番目のセットではなく、最初のセットに存在する要素によってのみ形成されます。関数によってコピーされる要素は、常に同じ順序で最初のセットから取得されます。両方のセットの要素はすでに注文されている必要があります。 一般的な集合演算は-です セットユニオン 交差点を設定 対称集合の差または排他的論理和 差または減算を設定 アルゴリズム Begin Declare set vector v and iterator st. Initialize st = set_difference (set1, set1 + n,