0

From MDN, javascript provides Map which is C++ equivalent to std::map. Is there a similar equivalent to unordered_map (providing O(1) insertions/lookup/deletion on avg).

Edit: As the answers suggest, std::unordered_map is more closer to javascript Map than std::map.

Abhijeet Khangarot
  • 923
  • 11
  • 22
  • 2
    I think you're just looking for [Object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object). – jsejcksn Aug 03 '21 at 21:49
  • According to [Map Objects](https://262.ecma-international.org/6.0/#sec-map-objects) I wouldn't say a JavaScript Map is equivalent to a C++ `std::map`: _"Map object must be implemented using either hash tables or other mechanisms that, on average, provide access times that are sublinear on the number of elements in the collection."_ A JavaScript Map can be implemented using hash tables providing O(1) insertions/lookup/deletion on avg. It's not ordered by the key but by insertion time. I'd say a JavaScript Map is more of a `std::unordered_map` than a `std::map`. – jabaa Aug 03 '21 at 22:02

1 Answers1

3

The equivalent of a JavaScript Map is the C++ unordered_map, as it provides sub-linear access (i.e. possibly logarithmic but constant in practice) and does not sort its keys. It keeps insertion order of elements for deterministic execution and cross-implementation compatibility, but it is not sorted.

There is no equivalent of the C++ map, which is implemented as a tree with comparable keys, in JavaScript.

Bergi
  • 572,313
  • 128
  • 898
  • 1,281