zoukankan      html  css  js  c++  java
  • 高效的使用stl::map和std::set

    1、低效率的用法
    // 先查找是否存在,如果不存在,则插入
    if (map.find(X) == map::end()) // 需要find一次
    {
        map.insert(x); // 需要find一次
    }
    // 下面这段代码是一个意思
    if (0 == map.count(X) // 需要find一次
    {
        map.insert(x); // 需要find一次
    }

    // 或者是先判断是否存在,如果不存在则插入,反之如果存在则修改
    if (map.count(X) > 0) // 需要find一次
    {
        map.erase(X); // 需要find一次
    }
    map.insert(x); // 需要find一次

    // 对于erase存在同样低效的用法
    if (map.count(X) > 0) // 需要find一次
    {
        map.erase(X); // 需要find一次
    }
    else
    {
        // 不存在时的处理
    }

    2、高效率的用法
    // 解决办法,充分利用insert和erase的返回值,将find次数降为1
    map::size_type num_erased = map.erase(X); // 需要find一次
    if (0 == num_erased)
    {
        // 不存在时的处理
    }
    else
    {
        // 存在且删除后的处理
    }

    pair<map::iterator, bool> result_inserted;
    result_inserted = map.insert(X);
    if (result_inserted.second)
    {
        // 不存在,插入成功后的处理
    }
    else
    {
        // 已经存在,插入失败后的处理
        result_inserted.first->second = X; // 修改为新值 
    }

  • 相关阅读:
    高级选项更改MathType数学公式样式
    tp 批量转码
    create the web service by yourshelf
    云通讯 添加群组
    sql 更新字段
    op bug 修复计划
    php ut8声明
    PHP 包含文件
    php 判断查询结果是否为空
    合并列值
  • 原文地址:https://www.cnblogs.com/aquester/p/9891845.html
Copyright © 2011-2022 走看看