2

I would like to know if is it possible to fill a QMap with only key, and then for each key add value.

for example, something like :

QMap<QString, QString> map;
map.insert("key", null (??));

Thanks for your answer

iAmoric
  • 1,787
  • 3
  • 31
  • 64

2 Answers2

3

Well, you can fill it with empty string values, then simply change the strings:

QMap<QString, QString> map;
map.insert("key", "");

// and later

map[key] = "something else";
dtech
  • 47,916
  • 17
  • 112
  • 190
3

Filling a map with only keys is not possible, however you can initialize it with null strings as values.

Note that in Qt there is a distinction between empty strings and null strings.

I would therefore initialize each element of the map as

map.insert("key", QString()); // map of null strings

as opposed to

map.insert("key", ""); // map of empty strings
Emerald Weapon
  • 2,392
  • 18
  • 29
  • Thanks, it is was I needed – iAmoric May 02 '17 at 08:31
  • You are right, I expected the string to be null if you pass a string with only a null character in it. Alas, Qt doesn't make sense much of the time. – dtech May 02 '17 at 08:38
  • @dtech This is a QString feature (shared by other Qt types as well) that I ended up finding quite neat. – Emerald Weapon May 02 '17 at 08:50
  • @dtech if you expect Qt to create a null string from an empty c-string, how would you create the empty string in the first place? It makes perfect sense as it is. I'm not sure if `nullptr` can be cast to `QString` as in `QString(nullptr)` should use the `QString(const char*)` constructor. – xander May 02 '17 at 09:40
  • @xander - there is no such thing as an empty C string, `""` implicitly contains one single character - the null termination. You are effectively passing a null, the string length will be evaluated as a null too. – dtech May 02 '17 at 09:54
  • Also, why would you want to create an empty string in the first place? What is the intent here, because how would I do that depends on why I want to do that. – dtech May 02 '17 at 09:55
  • @dtech For me "" is still an empty string, it doesn't matter if the underlying data contains 1 char (`\0`) or 0. For `QString:isEmpty()` to return true it can be a null string (`QString:IsNull()`) or empty string, there are reasons to differentiate those states. – xander May 02 '17 at 10:35
  • @xander I didn't say it is not beneficial to differentiate between empty and null, all I said it is logical to expect that passing C string with only a null should result in a null string. You can have a string that contains nothing but reserves space, that would be an empty string that is not null. – dtech May 02 '17 at 10:48