map::erase

从指定的位置移除元素或元素的大小映射的或移除与指定的键的元素。

iterator erase(
   iterator _Where
);
iterator erase(
   iterator _First,
   iterator _Last
);
size_type erase(
   const key_type& _Key
);

参数

  • _Where
    从映射要移除的元素的位置。

  • _First
    从映射中移除的第一个元素的位置。

  • _Last
    在从映射中移除的最后一个元素之外标识。

  • _Key
    从映射要移除的元素的键值。

返回值

对于前两个成员函数、指定保持在所有元素外的第一个元素中移除一双向迭代器或要映射到的末尾的指针,如果不存在这样的元素。

备注

这将返回类型不符合C++标准。

为第三个成员函数,返回从映射中移除了元素的数目。

备注

在某些情况下,此方法可能会引发 out_of_range 异常。

示例

当编译此示例与 /Wp64 标记或在64位平台时,警告的编译器C4267将生成。 有关此警告的更多信息,请参见 编译器警告(等级 3)C4267

// map_erase.cpp
// compile with: /EHsc
#include <map>
#include <iostream>

int main()
{
    using namespace std;
    map<int, int> m1, m2, m3;
    map<int, int>::iterator pIter, Iter1, Iter2;
    int i;
    map<int, int>::size_type n;
    typedef pair<int, int> Int_Pair;

    for (i = 1; i < 5; i++)
    {
        m1.insert(Int_Pair(i, i));
        m2.insert(Int_Pair(i, i*i));
        m3.insert(Int_Pair(i, i-1));
    }

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

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

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

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

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

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

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

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

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

要求

标头: <map>

命名空间: std

请参见

参考

map Class

map::max_size, map::clear, map::erase, 和 map::size

标准模板库