std::map vs. vector of vector

前端 未结 3 758
天命终不由人
天命终不由人 2021-01-26 17:33

I need a container to store a value (int) according to two attributes, source (int) and destination (int) i.e. when a source sends something to a destination, I need to store it

3条回答
  •  渐次进展
    2021-01-26 18:07

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

    you would want

    std::map>
    

    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> - 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
    

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

提交回复
热议问题