c++ access elements of the array in a map

arrays, c++, dictionary

Solution

Value types for maps must be default-constructible, using an expression `value_type()`, in order to access them via `[]`. For some mysterious reason, array types are not, as specified in C++11 5.3.2/2 (with my emphasis):

The expression T(), where T is a simple-type-specifier or typename-specifier for a non-array complete object type ... creates a prvalue of the specified type,which is value-initialized

The compiler gives that strange error when trying to value-initialise an array; the following gives the same error:

typedef double array[2];
array();

I suggest using a class type rather than `double[2]`: `std::array<double,2>`, `std::pair<double,double>`, or a `struct` containing two doubles. Such types are copyable, don't decay into a pointer (losing compile-time knowledge of the size) at the drop of a hat, and are generally easier to deal than a built-in array type.

If you're stuck with an old library that doesn't provide `std::array`, then you could use the very similar Boost.Array, or write your own simple class template to wrap an array.

Problem

Possible Duplicate: Using array as map value: Cant see the error Assume I have the following data structure: ``` std::map<size_t, double[2] > trace; ``` how can I access its elements with the operator[]? Essentially I want to do something like: ``` trace[0][0] = 10.0; trace[0][1] = 11.0; ``` In compiling these lines of code I get the following error: ``` /usr/include/c++/4.6/bits/stl_map.h:453:11: error: conversion from ‘int’ to non-scalar type ‘std::map<long unsigned int, double [2]>::mapped_type {aka double [2]}’ requested ``` comments?

Original source

Related problems