C++でSTLを使用するhashmap(共通動作)
2965 ワード
ネット上でhashmapとmapに関する簡単な操作内容が少なく、一部のブログの内容が複雑で理解しにくいことがわかりました.ここではわざわざ簡単なチュートリアルを共有します.
1.at():キー値に基づいてコンテナ内の要素を検索し、map要素の参照を返します.
e.g.
2.アクセス要素:順方向反復と逆方向反復.
begin():コンテナ内の最初の要素を指す反復器.反復器が要素にアクセスするとき.
e.g.
end(),rbegin(),rend()用法同上.
注意end()の戻り値がmapの最後の値を超えている場合はhashを組み合わせる.end() --;
3.hashmapのサイズ:size()メンバー関数;
hashmapを空にします:clear()メンバー関数;
2つのhashmap間の要素を交換します:swap();
e.g.
4.エレメントの検索:find()メンバー関数;
空かどうかを判断する:empty()メンバー関数;
統計hash_map内の要素の数:count(element);1(すなわち、その元素が現れる)か、0(すなわち、このような元素が現れない)かのいずれかである.
erase():異なるインデックスに基づいてスロット内の要素を消去します.
Insert():要素を挿入します.
e.g.ハッシュ表の一般的な操作コードの例:
1.at():キー値に基づいてコンテナ内の要素を検索し、map要素の参照を返します.
e.g.
#include
#include
#include
2.アクセス要素:順方向反復と逆方向反復.
begin():コンテナ内の最初の要素を指す反復器.反復器が要素にアクセスするとき.
e.g.
hash.begin();
end(),rbegin(),rend()用法同上.
注意end()の戻り値がmapの最後の値を超えている場合はhashを組み合わせる.end() --;
3.hashmapのサイズ:size()メンバー関数;
hashmapを空にします:clear()メンバー関数;
2つのhashmap間の要素を交換します:swap();
e.g.
hm1.swap(hm2);swap(hm1, hm2);
4.エレメントの検索:find()メンバー関数;
空かどうかを判断する:empty()メンバー関数;
統計hash_map内の要素の数:count(element);1(すなわち、その元素が現れる)か、0(すなわち、このような元素が現れない)かのいずれかである.
erase():異なるインデックスに基づいてスロット内の要素を消去します.
Insert():要素を挿入します.
e.g.ハッシュ表の一般的な操作コードの例:
#define _DEFINE_DEPRECATED_HASH_CLASSES 0
#include
#include
// , hash_map unordered_map
int main() {
using namespace std;
unordered_map hm1;
unordered_map ::const_iterator hm1_AcIter, hm1_RcIter;
typedef pair Int_Pair;
hm1.insert(Int_Pair(1, 10));
hm1.insert(Int_Pair(2, 20));
hm1.insert(Int_Pair(3, 30));
hm1.insert(Int_Pair(5, 50));
hm1_RcIter = hm1.find( 2 );
cout << "Key 2 : "
<< hm1_RcIter -> second << "." << endl;
// ->second (2,20) 20,->first (2,20) 2
// If no match is found for the key, end( ) is returned
hm1_RcIter = hm1.find(4);
//find() Key
if (hm1_RcIter == hm1.end())
cout << " Key 4 . "<< endl;
else
cout << "Key 4 : "
<< hm1_RcIter->second << "." << endl;
// The element at a specific location in the hash_map can be found
// using a dereferenced iterator addressing the location
hm1_AcIter = hm1.end();
// end() map , hash.end() --;
hm1_AcIter --;
hm1_RcIter = hm1.find(hm1_AcIter->first);
cout << " : "
<< hm1_RcIter->second << "." << endl;
int x = hm1.count(5);
cout << " 5 :" << x << endl;
int size = hm1.size();
cout << " :" << size << endl;
cin.get();
}