std::map<int, int> vs. vector of vector

喜夏-厌秋 提交于 2019-12-02 11:39:05

I need a container to store a value (int) according to two attributes, source (int) and destination (int)

std::map<std::pair<int, int>, int>

A subsequent process needs to check this container, to see if an element exists in for a particular source, and a particular destination - it will need to differentiate between an empty 'space' and a filled one.

std::map::find

http://www.cplusplus.com/reference/map/map/find/

The container has the possibility of being very sparse.

Use a std::map. The "correct" choice of a container is based on how you need to find things and how you need to insert/delete things. If you want to find things fast, use a map.

First of all, assuming you want an equivalent structure of vector<vector<int>>

you would want

std::map<int,std::vector<int>>

because for each key in a map, there is one unique value only.

If your sources are indexed very closely sequentially as 0...N, will be doing a lot of look-ups, and few deletions, you should use a vector of vectors.

If your sources have arbitrary IDs that do not closely follow a sequential order or if you are going to do a lot of insertions/deletions, you should use a map<int,vector<int>> - usually implemented by a binary tree.

To check the size of a vector, you use

myvec.size()

To check whether a key exists in a map, you use

mymap.count(ID) //this will return 0 or 1 (we cannot have more than 1 value to a key)

I have used maps for a while and even though I'm nowhere close to an expert, they've been very convenient for me to use for storing and modifying connections between data.

P.S. If there's only up to one destination matching a source, you can proceed with

map<int,int>

Just use the count() method to see whether a key exists before reading it

If you want to keep using a vector but want to add a check for whether the item contains a valid value, look at boost::optional. The type would now be std::vector<std::vector<boost::optional<int>>>.

You can also use a map, but the key into the map needs to be both IDs not just one.

std::map<std::pair<int,int>,int>

Edit: std::pair implements a comparison operator operator< that should be sufficient for use in a map, see http://en.cppreference.com/w/cpp/utility/pair/operator_cmp.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!