Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ access elements of the array in a map [duplicate]

Tags:

c++

arrays

map

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?

like image 234
arthur Avatar asked Nov 23 '12 10:11

arthur


People also ask

How do you find duplicate elements in an array using maps?

How To Find Duplicate Elements In Array In Java Using HashMap? In this method, We use HashMap to find duplicates in array in java. We store the elements of input array as keys of the HashMap and their occurrences as values of the HashMap. If the value of any key is more than one (>1) then that key is duplicate element.

How do you find duplicate elements in an array?

Duplicate elements can be found using two loops. The outer loop will iterate through the array from 0 to length of the array. The outer loop will select an element. The inner loop will be used to compare the selected element with the rest of the elements of the array.

How do I find duplicates in a HashMap?

Approach: The idea is to do hashing using HashMap. Create a hashMap of type {char, int}. Traverse the string, check if the hashMap already contains the traversed character or not. If it is present, then increment the count or else insert the character in the hashmap with frequency = 1.


1 Answers

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.

like image 77
Mike Seymour Avatar answered Oct 30 '22 12:10

Mike Seymour