Chinaunix首页 | 论坛 | 博客
  • 博客访问: 8064008
  • 博文数量: 594
  • 博客积分: 13065
  • 博客等级: 上将
  • 技术积分: 10324
  • 用 户 组: 普通用户
  • 注册时间: 2008-03-26 16:44
个人简介

推荐: blog.csdn.net/aquester https://github.com/eyjian https://www.cnblogs.com/aquester http://blog.chinaunix.net/uid/20682147.html

文章分类

全部博文(594)

分类: C/C++

2012-03-21 11:26:55

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

阅读(3982) | 评论(0) | 转发(2) |
给主人留下些什么吧!~~