开发者

std::map with a char[5] key that may contain null bytes

开发者 https://www.devze.com 2023-03-07 23:49 出处:网络
The keys are binary garbage and I only define开发者_JS百科d them as chars because I need a 1-byte array.

The keys are binary garbage and I only define开发者_JS百科d them as chars because I need a 1-byte array.

They may contain null bytes.

Now problem is, when I have a two keys: ab(0)a and ab(0)b ((0) being a null byte), the map treats them as strings, considers them equal and I don't get two unique map entries.

What's the best way to solve this?


Why not use std::string as key:

//must use this as:
std::string key1("ab\0a",4); 
std::string key2("ab\0b",4); 
std::string key3("a\0b\0b",5); 
std::string key4("a\0\0b\0b",6); 

Second argument should denote the size of the c-string. All of the above use this constructor:

string ( const char * s, size_t n );

description of which is this:

Content is initialized to a copy of the string formed by the first n characters in the array of characters pointed by s.


Use std::array<char,5> or maybe even better (if you want really to handle keys as binary values) std::bitset


If you really want to use char[5] as your key, consider writing your own comparison class to compare between keys correctly. The map class requires one of these in order to organize its contents. By default, it is using a version that doesn't work with your key.

Here's a page on the map class that shows the parameters for map. You'd want to write your own Compare class to replace less<Key> which is the third template parameter to map.


If you only need to distinguish them and don't rely on a lexicographical ordering you could treat each key as uint64_t. This has the advantage, that you could easily replace std::map by a hashmap implementation and that you don't have to do anything by hand.

Otherwise you can also write your own comparator somehow like this:

class MyKeyComp
{
  public:
  operator()(char* lhs, char* rhs)
  {
    return lhs[0] == rhs[0] ? 
       (lhs[1] == rhs[1] ? 
       (lhs[2] == rhs[2] ? 
       (lhs[3] == rhs[3] ? lhs[4] < rhs[4]) 
       : lhs[3] < rhs[3]) 
       : lhs[2] < rhs[2]) 
       : lhs[1] < rhs[1]) 
       : lhs[0] < rhs[0];
  }
};
0

精彩评论

暂无评论...
验证码 换一张
取 消