map is a standard container just like list or vector. It maps a key to a value. So if your class had some type of unique ID, you could map that ID to the class object. Then, when you want to get the object from the container, you just lookup the key instead of scanning each element trying to find it.
Code:
#include <iostream>
#include <map>
#include <string>
class my_data
{
public:
std::string text;
my_data(const char* t = "") : text(t) { }
};
int main()
{
std::map<int, my_data> data_map;
// insert new elements
data_map.insert(std::make_pair(1, my_data("one")));
data_map.insert(std::make_pair(1200, my_data("twelve hundred")));
data_map.insert(std::make_pair(5, my_data("five")));
// insert or change existing elements
data_map[10] = my_data("ten"); // insert
data_map[1200] = my_data("one thousand two hundred"); // change
data_map[77] = my_data("seventy seven"); // insert
// Look up a single element:
int lookup = 10;
std::map<int, my_data>::const_iterator one_item = data_map.find(lookup);
if (one_item != data_map.end())
std::cout << one_item->second.text << " (" << lookup << ")\n";
else
std::cout << lookup << " not found.\n";
lookup = 100;
one_item = data_map.find(lookup);
if (one_item != data_map.end())
std::cout << one_item->second.text << " (" << lookup << ")\n";
else
std::cout << lookup << " not found.\n";
// Lookup a single element (but automatically create a new one if it isn't there):
lookup = 5;
std::cout << data_map[lookup].text << " (" << lookup << ")\n";
lookup = 50;
std::cout << data_map[lookup].text << " (" << lookup << ")\n";
// Show everything in the map:
std::map<int, my_data>::const_iterator map_end = data_map.end();
for (one_item = data_map.begin(); one_item != map_end; ++one_item)
{
std::cout << "Key: " << one_item->first;
std::cout << " Value: \"" << one_item->second.text << "\"\n";
}
// done
std::cin.get();
}
(Note: I just typed this up, I didn't test it.) Notice how you can insert in any order, but the loop at the end outputs them in sorted order. Also notice how you can use operator[] or iterators and member functions to access the map contents. The lookups in the map are faster algorithmically than list lookups.