STL Map with a Vector for the Key

后端 未结 4 938
刺人心
刺人心 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:36

    Why do you need a std::map for that? Maybe I miss some point but what about using an std::vector together with the find algorithm as examplained here?

    This means, that you append your unsigned ints to the vector and later search for it, e.g.

    std::vector<unsigned int> collector; // vector that is substituting your std::map
    for(unsigned int i=0; i<myInts.size(); ++i) {  // myInts are the long ints you have
        if(find(collector.begin(), collector.end(), myInts.at(i)==collector.end()) {
             collector.push_back(myInts.at(i));
        }
    }
    
    0 讨论(0)
  • 2020-12-30 04:38

    You will not have problems with that, as std::vector provides you the "==", "<" and ">" operators:

    http://en.cppreference.com/w/cpp/container/vector/operator_cmp

    0 讨论(0)
  • 2020-12-30 04:49

    The requirements for being a key in std::map are satisfied by std::vector, so yes you can do that. Sounds like a good temporary solution (easy to code, minimum of hassle) -- but you know what they say: "there is nothing more permanent than the temporary".

    0 讨论(0)
  • 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 <vector>
    #include <map>
    #include <utility>
    
    // typedefs help a lot to shorten the verbose C++ code
    typedef std::map<std::vector<unsigned char>, int> MyMapType;
    
    std::vector<unsigned char> v = ...; // initialize this somehow
    std::pair<MyMapType::iterator, bool> 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
    }
    
    0 讨论(0)
提交回复
热议问题