【问题标题】:What is the difference between clear and erase methods provided by std::map?std::map 提供的 clear 和 erase 方法有什么区别?
【发布时间】:2022-11-17 14:09:30
【问题描述】:

查看方法名称擦除清除, 两者都倾向于执行与清除 std::map 的内容相关的操作

哪种方法适合哪种场景,请举例说明。

【问题讨论】:

    标签: c++ stl containers stdmap associative


    【解决方案1】:

    std::map::erase 可用于从地图中删除特定元素或元素范围,方法是使用迭代器或键提供删除条件

    map<string, int> table;
    table[apple] = 1;
    table[mango] = 2;
    table[orange] = 3;
    
    auto itr = table.find("mango");
    table.erase(itr);                   
    table.erase("orange"); 
    

    std::map::clear会抹掉地图的全部内容,

    map<string, int> table;
    table[apple] = 1;
    table[mango] = 2;
    table[orange] = 3;
    
    cout<<"Before clear: "<<table.size()<<"
    ";
    table.clear();
    cout<<"After clear: "<<table.size()<<"
    ";
    

    根据情况需要,在两者中选择你自己的毒药

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-15
      • 2018-05-14
      • 1970-01-01
      • 2011-03-24
      • 1970-01-01
      • 2011-08-31
      相关资源
      最近更新 更多