Programming: several C++ container classes
|
In our live Arkanoid coding sessions, we used several standard C++ container classes. I am going to describe them in this post. std::pair An array contains multiple elements of the same type. Sometimes, however, it is useful to hold two objects (possibly of different types) as a single entity. For this purpose, we use the Below is a table with basic personal data:
It is natural to group Id and Name and refer to them as a single object within the body of a program. The following declaration establishes this grouping: int id = 100; std::string name = “John”; std::pair entry (id, name); You can now refer to the object entry which contains both the id = 100 and the name = John.
std::cout << entry.first << std::endl; std::cout << entry.second; The above code would produce std::map Suppose you want to contain a number of such
Here you would use the int john = 100; std::string John = “John”; std::pair entry1 (john, John); int mary = 101; std::string Mary = “Mary”; std::pair entry2 (mary, Mary); int peter = 102; std::string Peter = “Peter”; std::pair entry3 (peter, Peter); std::map people; people.insert(entry1); people.insert(entry2); people.insert(entry3); The code above declares the map people and adds the three Accessing the pairs and their elements is a little bit more involved. Let’s say I want to refer to the second entry (Mary). Then I have to define something called an iterator. An iterator is a special pointer that points to a particular element in a container class like auto it = people.find(101); you will create an iterator, Once the iterator is set up, you can use it to obtain the actual elements of that std::cout << (*it).second << std::endl; The above line is equivalent to std::cout <second << std::endl; where the NB: auto refers to the type of the iterator we’re defining. Since I’m creating an iterator for an std::map::iterator it = people.find(101); which explicitly defines the type of the iterator – it belongs to an |