📌  相关文章
📜  如何在C++中从地图中删除最后一个元素

📅  最后修改于: 2021-05-30 17:40:47             🧑  作者: Mango

如果我们希望从地图中删除最后一个元素,可以使用以下方法:

  1. 使用prev(mp.end()) :prev函数的作用是,它从给定的迭代器后退了一步。因此,将prev函数与mp.end()结合使用将返回一个迭代器,该迭代器指向地图的最后一个元素。
    执行:
    #include 
      
    using namespace std;
      
    int main()
    {
      
        map mp;
      
        // Adding some elements in mp
        mp[1] = 10;
        mp[2] = 20;
        mp[3] = 30;
      
        cout << "Contents of mp before deleting"
               " the last element :\n";
        for (auto it = mp.begin(); it != mp.end(); it++)
            cout << it->first << " ==> "
                 << it->second << "\n";
      
        cout << "Deleting the last element from"
               " the map.\n";
        mp.erase(prev(mp.end()));
      
        cout << "Contents of mp after deleting the last"
                " element :\n";
        for (auto it = mp.begin(); it != mp.end(); it++)
            cout << it->first << " ==> "
                 << it->second << "\n";
    }
    
    输出:
    Contents of mp before deleting the last element :
    1 ==> 10
    2 ==> 20
    3 ==> 30
    Deleting the last element from the map.
    Contents of mp after deleting the last element :
    1 ==> 10
    2 ==> 20
    
  2. using iterator– :将迭代设置为mp.end(),然后使用iterator–到达映射中的最后一个元素,然后使用擦除函数将其删除。
    执行:
    #include 
      
    using namespace std;
      
    int main()
    {
      
        map mp;
        // Adding some elements in mp
        mp[1] = 10;
        mp[2] = 20;
        mp[3] = 30;
      
        cout << "Contents of mp before deleting "
                "the last element :\n";
        for (auto it = mp.begin(); it != mp.end(); it++)
            cout << it->first << " ==> " 
                 << it->second << "\n";
      
        cout << "Deleting the last element from"
                " the map.\n";
        auto it = mp.end();
        it--;
        mp.erase(it);
      
        cout << "Contents of mp after deleting the"
                " last element :\n";
        for (auto it = mp.begin(); it != mp.end(); it++)
            cout << it->first << " ==> "
                 << it->second << "\n";
    }
    
    输出:
    Contents of mp before deleting the last element :
    1 ==> 10
    2 ==> 20
    3 ==> 30
    Deleting the last element from the map.
    Contents of mp after deleting the last element :
    1 ==> 10
    2 ==> 20
    
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”