STLにマップを実装するC++プログラム
マップは、マップされた方法で要素を格納する連想コンテナです。各要素には、キー値とマップされた値があります。 2つのマップされた値が同じキー値を持つことはできません。
ここで使用される関数:
-
m ::find()–見つかった場合は、マップ内のキー値「b」を持つ要素にイテレータを返します。それ以外の場合は、終了するイテレータを返します。
-
m ::Erase()–マップからキー値を削除します。
-
m ::equal_range()–ペアのイテレータを返します。ペアは、キーと同等のキーを持つコンテナ内のすべての要素を含む範囲の境界を指します。
-
m insert()–マップコンテナに要素を挿入します。
-
m size()–マップコンテナ内の要素の数を返します。
-
m count()–マップ内のキー値が「a」または「f」の要素と一致する数を返します。
サンプルコード
#include<iostream>
#include <map>
#include <string>
using namespace std;
int main () {
map<char, int> m;
map<char, int>::iterator it;
m.insert (pair<char, int>('a', 10));
m.insert (pair<char, int>('b', 20));
m.insert (pair<char, int>('c', 30));
m.insert (pair<char, int>('d', 40));
cout<<"Size of the map: "<< m.size() <<endl;
cout << "map contains:\n";
for (it = m.begin(); it != m.end(); ++it)
cout << (*it).first << " => " << (*it).second << '\n';
for (char c = 'a'; c <= 'd'; c++) {
cout << "There are " << m.count(c) << " element(s) with key " << c << ":";
map<char, int>::iterator it;
for (it = m.equal_range(c).first; it != m.equal_range(c).second; ++it)
cout << ' ' << (*it).second;
cout << endl;
}
if (m.count('a'))
cout << "The key a is present\n";
else
cout << "The key a is not present\n";
if (m.count('f'))
cout << "The key f is present\n";
else
cout << "The key f is not present\n";
it = m.find('b');
m.erase (it);
cout<<"Size of the map: "<<m.size()<<endl;
cout << "map contains:\n";
for (it = m.begin(); it != m.end(); ++it)
cout << (*it).first << " => " << (*it).second << '\n';
return 0;
} 出力
Size of the map: 4 map contains: a => 10 b => 20 c => 30 d => 40 There are 1 element(s) with key a: 10 There are 1 element(s) with key b: 20 There are 1 element(s) with key c: 30 There are 1 element(s) with key d: 40 The key a is present The key f is not present Size of the map: 3 map contains: a => 10 c => 30 d => 40
-
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,