std::vector, std::unordered_map, and std::unordered_set.

Recently I’ve seen a couple of examples of bad choses when it comes to what containers to use in the code, so I thought I’d share my view of some containers.

 

When you need an associative container (key -> value map) use std::unordered_map, if it is important to be able to loop over the items in order use std::map.

 

When you need to ensure that the container only has one of each value use std::unordered_set, if it is important to be able to loop over the items in order use std::set.

 

For almost all other cases use std::vector (or, if the number of elements is fixed std::array).

 

In some situations, std::deque might be useful, for example when modelling a queue.

 

If you are not sure which container to use, go with std::vector!

 

 

There is also std::list and std::forward_list, which should probably never be used. There are very, very, few situations in which a std::list is better than a std::vector or an std::vector containing pointers, so it is best to avoid using them unless you know exactly what you are doing and have ran the relevant tests in ST and std::list was still better than std::vector.

 

There are also the adaptors (std::stack, std::queue, and std::priority_queue) which can be useful in some scenarios, but please notice that these are not real containers, they are wrappers around a container, so when using them consider what would be a good container to use as a base).

 

There is also the std::multiset, std::multimap, std::unordered_multiset, and std::unordered_multimap, which are rarely needed, and in many cases a vector might work just as well.

 

 

Conclusion: For most of your needs you should only use std::vector, std::unordered_map, and std::unordered_set.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值