STL Map with a Vector for the Key

后端 未结 4 942
刺人心
刺人心 2020-12-30 04:32

I\'m working with some binary data that I have stored in arbitrarily long arrays of unsigned ints. I\'ve found that I have some duplication of data, and am looking to igno

4条回答
  •  温柔的废话
    2020-12-30 04:50

    That should work, as Renan Greinert points out, vector<> meets the requirements to be used as a map key.

    You also say:

    I'm looking at inserting each dataset into a map before storing it, but only if it was not found in the map to start with.

    That's usually not what you want to do, as that would involve doing a find() on the map, and if not found, then doing an insert() operation. Those two operations would essentially have to do a find twice. It is better just to try and insert the items into the map. If the key is already there, the operation will fail by definition. So your code would look like this:

    #include 
    #include 
    #include 
    
    // typedefs help a lot to shorten the verbose C++ code
    typedef std::map, int> MyMapType;
    
    std::vector v = ...; // initialize this somehow
    std::pair result = myMap.insert(std::make_pair(v, 42));
    if (result.second)
    {
       // the insertion worked and result.first points to the newly 
       // inserted pair
    }
    else
    {
       // the insertion failed and result.first points to the pair that
       // was already in the map
    }
    

提交回复
热议问题