Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

char

stl

stdmap

The keys are binary garbage and I only defined 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?

like image 432
George Stephanos Avatar asked Jun 01 '26 12:06

George Stephanos


2 Answers

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.

like image 163
Nawaz Avatar answered Jun 03 '26 01:06

Nawaz


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

like image 35
log0 Avatar answered Jun 03 '26 01:06

log0