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; // 修改为新值 
}