Click here to Skip to main content
15,916,835 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am reading a book called jumping into C++ by Alex Allain and he has introduced maps with lines of code like:

map<string, string> name_to_email;

name_to_email[ "Alex Allain" ] = "webmaster@cprogramming.com";

cout << name_to_email[ "Alex Allain" ];


And he keeps saying how useful maps are but the problem is, I can't understand what their benefit is. Their size can be changed (like a linked list, binary tree or vector), they can store multiple values per node (like a linked list or binary tree) and they can store values of different types (like a linked list or binary tree). So what exactly is it that makes these maps useful. Explain in simple terms please as I will struggle to understand sophisticated programming terms.

What I have tried:

I have tried reading the books explanation about why maps are used and tried reading explanations online about why they're used but couldn't really understand either.
Posted
Updated 12-Jun-18 9:57am

1 solution

The primary reason they are so useful is they make searching and finding values of interest very fast. The first item in the map is called the key and it used for searching. Usually a binary tree or something similar holds the data behind the scenes with the first value being the identifier searches are looking up. The speed of the searching is the strength of maps.
 
Share this answer
 
Comments
CPallini 12-Jun-18 16:06pm    
5.
BerthaDusStuf 12-Jun-18 17:19pm    
So it is the fact that u can use a variable to get an index that makes them good for searching?
Rick York 12-Jun-18 20:15pm    
Yes, and the fact that it is one of the fastest algorithms for searching available. The speed is really the most important point here. There are lots of algorithms that support searching for a keyed value but very few are as fast and efficient as std::map is and that is why it is part of the standard library. You could use a simple vector or list of structures and a linear search to find the key but with a large set of data that can be too slow. A map will speed things up considerably.
BerthaDusStuf 13-Jun-18 14:50pm    
oh ok thanks, also do you know whether maps are built like arrays or like linked lists or what sort of data structure are they?
Rick York 14-Jun-18 11:01am    
I am not certain, because I don't have to be :) but I think they are closer to an array (vector actually) because I think it uses a binary search algorithm and those usually have an ordered array inside.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900