一些map优化的办法

部署运行你感兴趣的模型镜像

std::map用于key-value式的查询,增加map的效率的办法:
1. 使用emplace代替insert. 直接构建key-value对象

map.emplace(std::piecewise_construct,
            std::forward_as_tuple(i,"x"),
            std::forward_as_tuple(i));

2. key减少对std::string的依赖
std::string可能会发生对动态内存的申请。

class Key {
    int a_;
    std::string b_;
public:
    Key(int a, std::string b) :a_(a), b_(b) {}

    bool operator<(const Key& other) {
        if (a_ != other.a_) {
            return a_ < other.a_;
        }
        else {
            if (b_ != other.b_) {
                return b_ < other.b_;
            }
            else {
                return false;
            }
        }
    }
};

3. 为了保证严格弱排序,小于操作符的实现注意:当对象值相等时,永远返回false。
为了实现这一点,例2中的operator<已经非常复杂了,当考虑进入更多成员时,将极易出错。现在有了std::tie解决这个问题
 

class Key {
    int a_;
    std::string b_;
    std::string c_;
public:
    Key(int a, std::string&& b, std::string&& c) 
        :a_(a), b_( std::move(b) ), c_(std::move(c))
    {}

    bool operator<(const Key& other) {
        return std::tie(a_, b_, c_) < std::tie(other.a_, other.b_, other.c_);
    }
};

4. 自定义分配器,通过boost内存池获取

实测并未增加效率
 

#include <boost/pool/pool_alloc.hpp>
typedef std::map<Key, int >::value_type pair_type;
typedef std::map<Key, int, less_op, boost::pool_allocator<pair_type> > map_type;
map_type map;

 

您可能感兴趣的与本文相关的镜像

ACE-Step

ACE-Step

音乐合成
ACE-Step

ACE-Step是由中国团队阶跃星辰(StepFun)与ACE Studio联手打造的开源音乐生成模型。 它拥有3.5B参数量,支持快速高质量生成、强可控性和易于拓展的特点。 最厉害的是,它可以生成多种语言的歌曲,包括但不限于中文、英文、日文等19种语言

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值