首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ Builder >

怎么删除hash_map 中的KEY

2012-02-21 
如何删除hash_map 中的KEY - C++ Builder / Windows SDK/API小弟最近用到hash_map 要通过遍历hash_map元素

如何删除hash_map 中的KEY - C++ Builder / Windows SDK/API
小弟最近用到hash_map 要通过遍历hash_map元素进行逻辑判断。 但是当我删除hash_map中的某个KEY对应的值后,
该key依然存在,请问如何将KEY和它所对应的值一并删除 。谢谢

[解决办法]
erase
[解决办法]

C/C++ code
 
// hash_map_erase.cpp
// compile with: /EHsc
#define _DEFINE_DEPRECATED_HASH_CLASSES 0
#include <hash_map>
#include <iostream>

int main()
{
  using namespace std;
  using namespace stdext;
  hash_map <int, int> hm1, hm2, hm3;
  hash_map <int, int> :: iterator pIter, Iter1, Iter2;
  int i;
  hash_map <int, int>::size_type n;
  typedef pair <int, int> Int_Pair;

  for (i = 1; i < 5; i++)
  {
    hm1.insert(Int_Pair (i, i));
    hm2.insert(Int_Pair (i, i*i));
    hm3.insert(Int_Pair (i, i-1));
  }

  // The 1st member function removes an element at a given position
  Iter1 = ++hm1.begin();
  hm1.erase(Iter1);

  cout < < "After the 2nd element is deleted, the hash_map hm1 is:";
  for (pIter = hm1.begin(); pIter != hm1.end(); pIter++)
    cout < < " " < < pIter -> second;
  cout < < "." < < endl;

  // The 2nd member function removes elements
  // in the range [_First, _Last)
  Iter1 = ++hm2.begin();
  Iter2 = --hm2.end();
  hm2.erase(Iter1, Iter2);

  cout < < "After the middle two elements are deleted, "
    < < "the hash_map hm2 is:";
  for (pIter = hm2.begin(); pIter != hm2.end(); pIter++)
    cout < < " " < < pIter -> second;
  cout < < "." < < endl;

  // The 3rd member function removes elements with a given _Key
  n = hm3.erase(2);

  cout < < "After the element with a key of 2 is deleted,\n"
    < < "the hash_map hm3 is:";
  for (pIter = hm3.begin(); pIter != hm3.end(); pIter++)
    cout < < " " < < pIter -> second;
  cout < < "." < < endl;

  // The 3rd member function returns the number of elements removed
  cout < < "The number of elements removed from hm3 is: "
    < < n < < "." < < endl;

  // The dereferenced iterator can also be used to specify a key
  Iter1 = ++hm3.begin();
  hm3.erase(Iter1);

  cout < < "After another element with a key equal to that"
    < < endl;
  cout  < < "of the 2nd element is deleted, "
    < < "the hash_map hm3 is:";
  for (pIter = hm3.begin(); pIter != hm3.end(); pIter++)
    cout < < " " < < pIter -> second;
  cout < < "." < < endl;
}


Output

After the 2nd element is deleted, the hash_map hm1 is: 1 3 4.
After the middle two elements are deleted, the hash_map hm2 is: 1 16.
After the element with a key of 2 is deleted,
the hash_map hm3 is: 0 2 3.
The number of elements removed from hm3 is: 1.
After another element with a key equal to that
of the 2nd element is deleted, the hash_map hm3 is: 0 3.

热点排行