ladyfafa
ladyfafa

Reputation: 7269

what C++ map mean?

I have the following C++ map example code:

map<string,string> &weight2price  
....  
weight = ...  
price = ...  
if(weight2price.find(weight) == weight2price.end())  
    weight2price[weight] = price;

could anyone tell me what it means by

if(weight2price.find(weight) == weight2price.end())

Upvotes: 3

Views: 7423

Answers (4)

iniju
iniju

Reputation: 1094

map in C++ is a like hashmap, where a key (in your case weight) is mapped to a value (price).

Here it checks to see if the particular weight is already mapped in this map, if not the find method will return weight2price.end()

In that case the program enters a key-value pair in the map with the line that you greyed out.

Upvotes: 0

Ioan Paul Pirau
Ioan Paul Pirau

Reputation: 2833

The STL Map is a standard C++ container. It uses unique keys that can be compared to refer to value data being stored inside the container. It works much like an array but unlike an array, the key can be anything and doesn't need to be an integer. The syntax for a map is:

std::map < Key, Data, Compare, Alloc>

Key - the type of object that will be used as key
Data - the type of object that will be used as data
Compare - a comparison function for the keys
Alloc - The map's allocator, used for all internal memory management

usage:

map[Key] = Data

For further reading about STL maps look here : http://en.wikipedia.org/wiki/Map_%28C%2B%2B%29 and here: http://www.sgi.com/tech/stl/Map.html

In the code snippet, you are using the function find() from the map. This function returns an iterator pointing to the element from the map that contains the key you were searching for. If that key is not found, the find function will return the iterator pointing to the end of the map. That is what is being checked in the code snippet you attached to your question and if the find function returned the value of the end iterator, this means that the key is not in the map, so it adds the key and data to the map. An optimization for your code was provided by GMan in his comment.

A very basic explanation for an iterator (although not complete) would be that an iterator is a pointer to a pair< Key,Data>.

Hope this helps!

Upvotes: 8

GManNickG
GManNickG

Reputation: 503785

If the key passed to find() does not exist, find() returns end(). So it's saying "If it wasn't found...".

The code could be written better as:

weight2price.insert(std::make_pair(weight, price));

So look-up isn't done twice. (If the key already exists, insert won't do anything.)

Upvotes: 7

deinst
deinst

Reputation: 18772

It means that weight was not found. Then if it wasn't found, it adds it.

Upvotes: 1

Related Questions