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
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 int
s 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));
}
}
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
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".
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
}