How to loop through Undordered Maps C++

Looping through unordered maps in C++ is quite simple if you know what a range-based for loop is. If you don’t know what a range-based for loop is, click here. The code looks like this:

for (auto item : m_objectList)
 {
        item.second.SendData();
 }

This works exactly like a normal range-based for loop with one key difference. When you reference the iterator, you have to choose either .first or .second before accessing any data stored in the list.

.first refers to the ‘key’ identifier in your unordererd_map.

.second refers to the data stored at that iterator.

If you are not sure what I mean by ‘key’ identifier, it’s how you placed data into your list in the first place, like so:

m_objectList[ID] = object;

So .first in this case would refer to your ID.

.second is all of the public variables and functions of the iterator.

int temp;
temp = item.first;

The above code accesses the ID of your iterator and assigns it to a temporary int.

item.second.SendData();

Accesses the actual data stored at the iterator, in this case a public function called SendData().

If you enjoyed reading, try my game Puzzledorf out on Steam and Humble Bundle.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Blog at WordPress.com.

Up ↑

%d bloggers like this: