-1

After inizialized a QMap in the .h file in this way

QMap<QString, QString> *map;

When I declare in the constructor

map = new QMap<QString, QString>;
map["one"] = "foobar";

error: invalid types 'QMap*[const char [4]]' for array subscript map["one"] = "foobar"; ^

Where is the problem?

demonplus
  • 5,613
  • 12
  • 49
  • 68
user3713179
  • 361
  • 3
  • 12

3 Answers3

1

You need to dereference the map pointer.

map = new QMap<QString, QString>;
map["one"] = "foobar";

Should be:

map = new QMap<QString, QString>;
(*map)["one"] = "foobar";

This is because map is a pointer to an object; *map returns a reference to the object.

The compiler error message is not very helpful, because the compiler assumes that for a pointer p, p[expr] is an array subscript operation.

NicholasM
  • 4,557
  • 1
  • 20
  • 47
0

map is a pointer. Pointers happen to have a built-in operator[], which is why the error message may appear a bit strange at first glance. It has nothing to do with QMaps's overloaded operator[], actually.

Consider this:

int array[123];
array["one"] = "foobar";

It will produce the same error:

error: invalid types ‘int [123][const char [4]]’ for array subscript
 array["one"] = "foobar";

To get to the pointed-to-type (QMap in this case), you have to dereference the pointer: *map.

It will then work fine:

(*map)["one"] = "foobar";
Christian Hackl
  • 27,051
  • 3
  • 32
  • 62
0

As the others says you must dereference the map if you create in that way. But if you create your map on stack instead of on the heap (remove the *) than it will be easier.

In your header file:

QMap< QString, QString > map;

In your source file (remove the line with the new keyword):

map[ "one" ] = "foobar";
p.i.g.
  • 2,815
  • 2
  • 24
  • 41