Accessing map value by index

前端 未结 6 2052
时光取名叫无心
时光取名叫无心 2020-12-01 14:34

If I have a structure like

std::map myMap;
myMap[\"banana\"] = 1;
myMap[\"apple\"] = 1;
myMap[\"orange\"] = 1;

How can I

6条回答
  •  眼角桃花
    2020-12-01 14:56

    Well, actually you can't. The way you found is very unefficient, it have a computational complexity of O(n) (n operations worst case, where n is the number of elements in a map).

    Accessing an item in a vector or in an array have complexity O(1) by comparison (constant computational complexity, a single operation).

    Consider that map is internally implemented as a red black tree (or avl tree, it depends on the implementation) and every insert, delete and lookup operation are O(log n) worst case (it requires logarithm in base 2 operations to find an element in the tree), that is quite good.

    A way you can deal with is to use a custom class that have inside both a vector and a map. Insertion at the end of the class will be averaged O(1), lookup by name will be O(log n), lookup by index will be O(1) but in this case, removal operation will be O(n).

提交回复
热议问题