10. Lists and Maps

About this Tutorial –

Objectives –

This course is aimed at students who need to get up to speed in C++. The course introduces object-oriented concepts and shows how they are implemented in C++. The course does not require awareness or familiarity with object-oriented programming techniques, but programming experience would be useful but not necessarily required.

Audience

Students who are new to object orientation (or programming) and need to learn C++.

Prerequisites

No previous experience in C++ programming is required. But any experience you do have in programming will help. Also no experience in Visual Studio is required. But again any experience you do have with programming development environments will be a valuable.

Contents

The C++ course covers these topics and more:

  • Introduction to C++: Key features of C++; Defining variables; Formulating expressions and statements; Built-in data types; Console input/output
  • Operators and types: Assignment; Compound Assignment; Increment and decrement operators; Const declarations; Type conversions
  • Going Further with Data Types: Enumerations; Arrays; Using the standard vector class; Using the standard string class; Structures

Download Solutions

Java tutorial

Quick Access


Overview

Estimated Time – 0.5 Hours

Not what you are looking? Try the next tutorial – Inheritance

Lab 1: Using list

Lab 1: Using list
  1. What is list?
    • list is a standard C++ class
      • Defined in <list>
      • You also need a using namespace std;
    • Differences between list and vector
      • list
        • You can insert/remove items at any position – and this is the main reason for using list rather than vector
        • You have to use an iterator to specify the position
        • You can’t use [] notation
      • vector
        • You can only insert/remove items at the end (via push_back and pop_back)
        • You can use an iterator to specify the position
        • You can also use [] notation to specify a position
  2. Creating a list
    • When you create a list object, you must specify what type of elements it will contain, using <…> notation
      • Same as for vector
        #include <list>
        using namespace std;
        int main()
        {
         list<int>  ages;    // Empty list of ints
         list<Person> people;   // Empty list of Persons.
         list<int> marks(8, 100); // Eight ints with value 100 
         ...
        }
  3. Adding Items to a list
    • You can add items anywhere in a list
      • E.g. you can insert at the end, using push_back()
      • E.g. you can insert at the start, using push_front()
    • You can insert somewhere in the middle of a list
      • Using insert()
      • You also require an iterator that specifies the insertion point
    • To set the iterator to the desired position:
      • First call the list’s begin() or end() method, to position the iterator at the beginning or end
      • Then ++ or — the iterator, to move it forward/backward
        list<int> marks;
        ...
        // Create an iterator that points to the first element.
        list<int>::iterator iter = marks.begin();
        // Move the iterator onto the next element, just like incrementing a pointer
        iter++;
        // Access element at that position.
        cout << *iter;
  4. Removing Items from a list
    • You can remove items anywhere in a list
      • E.g. you can remove at the end, using pop_back()
      • .g. you can remove at the start, using pop_front()
      • E.g. you can remove at a general position, using erase()
    • When you use erase()...
      • You must either pass in a single iterator parameter
        • Indicates the position to erase
      • Or you must pass in two iterator parameters
        • Indicates a range to erase
        • The 1st iterator points to the first item to erase
        • The 2nd iterator points (one after) the last item to erase
  5. Looping through Elements
    • To loop through a list, you must use iterators
      list<int> marks;
      ...
      list<int>::iterator iter; // Create an iterator, to iterate over a list<int>.
      for (iter = marks.begin(); iter != marks.end(); iter++) // Loop through list.
      {
       cout << *iter; // Get contents at the current position. }
  6. For More Information...
    • There are lots of other cool features in list, here are some examples:
      • remove()
        • Removes all items that have a particular value
      • reverse()
        • Reverses the items in the list
      • sort()
        • Sorts the items in the list
    • For complete information about the list class, see:
      • https://www.cplusplus.com/reference/stl/list/
Lab
  1. Defining simple classes
    • In Visual Studio, create a new C++ project named ListsMapsApp in the student folder
    • Define two simple classes:
      • A simple Employee class (name and salary, plus PayRise() and ToString() methods)
        Employee::Employee(const string & name, double salary)
         : name(name) , salary(salary)
        {}
        Employee::~Employee()
        {}
        void Employee::PayRise(double rise)
        {
         salary += rise;
        }
        string Employee::ToString() const
        {
         stringstream oss;
         oss << "Name: " << name << " Salary: " << salary;  return oss.str(); }
      • View code file.
      • A simple Office class (city and country, plus a ToString() method)Office::Office(const string & city, const string & country)
         : city(city), country(country)
        {}
        Office::~Office()
        {}
        string Office::ToString() const
        {
         stringstream oss;
         oss << "Office City: " << city << " Office Country: " << country;  return oss.str(); }
      • View code file.
    • In main(), write code to test your classes
      string country="england",city="london",name="John Smith";
      Office o1(city,country);
      Employee e1(name,50000);
      cout << o1.ToString() << endl; cout << e1.ToString() << endl;
    • View code file.

Lab 2: Using map

Lab 2: Using map
  1. What is map?
    • map is yet another a standard C++ class
      • Defined in <map>
      • You also need a using namespace std;
    • Differences between map and list/vector
      • map
        • Each item in a map is a key-value pair
        • You access an item by "looking up" its key, not by its position
        • No inherent ordering
      • list/vector
        • Each item in a list/vector is the object itself
        • You access an item by its position (using iterators and/or [])
        • No way to "look up" an item - you would have to loop through to find it
  2. Creating a map
    • When you create a map object, you must specify two type parameters:
      • The data type of the key (usually a string or int)
      • The data type of the value (usually a class type, e.g. Employee)
        #include <map>
        using namespace std;
        int main()
        {
         // Create a map of employees.
         // The "key" type is string, and the "value" type is Employee.
         
         map<string, Employee> employees;
        ...
        }
  3. Accessing Items in a Map
    • To access items in a map:
      • Use the [] operator
      • Inside the [], specify an appropriate key value
      • Returns the value with that key (if the key doesn't exist, the map automatically creates a new item and returns it)
    • Example:
      // Create a map where the keys are strings, and the values are Employee objects
      map<string, Employee> employees;
      // Insert some items (not shown here).
      ...
      // Do a look-up to find the employee whose key is "abc123".
      Employee emp = employees["abc123"];
  4. Adding Items to a map
    • You can use [] to add an item to a map
      • Use [] on the left-hand-side of an assignment
      • Specify your object on the right-hand-side of the assignment
      • Note: if there's already an item with that key, the item is overwritten
    • Example:
      // Create a map where the keys are strings, and the values are Employee objects
      map<string, Employee> employees;
      // Insert some items.
      employees["scfc1"] = Employee("Michel Vorm", "Super keeper");
      employees["scfc5"] = Employee("Alan Tate", "Legend");
      employees["scfc8"] = Employee("Joe Allen", "Dynamic midfielder");
      ...
      // Also use [] to get an item (returns an Employee object in this example).
      employees["scfc1"].Display();
Lab
  1. Defining a container class
    • Define a Company class as follows:
      • The company has a list of offices, which can increase and decrease randomly
        list<Office> offices;
        void Company::AddOffice(Office o)
        {
         offices.push_back(o);
        }
        void Company::RemoveOffice(const string &city, const string &country)
        {
         for (list<Office>::iterator iter = offices.begin();
           iter != offices.end();
           iter++)
         {
          if (iter->GetCountry() == country && iter->GetCity() == city)
          {
           offices.erase(iter);
           break;
          }
         }
        }
        void Company::DisplayOffices() const
        {
         for (list<Office>::const_iterator iter = offices.begin();
           iter != offices.end();
           iter++)
         {
          cout << iter->ToString() << endl;  } }
      • View code file.
      • The company also has a map of employees, keyed by employee ID. Add functionality to find an employee by ID, add employees, see if an ID is already present, give a specified employee a pay rise, etc...
        map<int, Employee> employees;
        void Company::DisplayEmployee(int id)
        {
         cout << employees[id].ToString() << endl; } void Company::AddEmployee(Employee e,int id) {  if (AlreadyExists(id))  {   cout << "id already exists!" << endl;  }  else  {   employees[id] = e;  } } bool Company::AlreadyExists(int id) const {  return employees.find(id) != employees.end(); } void Company::GivePayrise(int id, double amount) {  if (AlreadyExists(id))  {   employees[id].PayRise(amount);  } }
      • View code file.
    • In main(),write code to test this new functionality
      Company c;
      c.AddOffice(o1);
      c.DisplayOffices();
      c.RemoveOffice(city,country);
      c.DisplayOffices();
      c.AddEmployee(e1,1);
      c.AddEmployee(e2,2);
      c.AddEmployee(e3,3);
      c.AddEmployee(e4,4);
      c.DisplayEmployee(1);
      c.DisplayEmployee(2);
      c.DisplayEmployee(3);
      c.DisplayEmployee(4);
      c.AddEmployee(e5,4);
      c.GivePayrise(4,500);
      c.DisplayEmployee(4);
    • View code file.

 

Well done. You have completed the tutorial in the C++ course. The next tutorial is

11. Inheritance


Back to beginning
Copyright © 2016 TalkIT®






If you liked this post, please comment with your suggestions to help others.
If you would like to see more content like this in the future, please fill-in our quick survey.
Scroll to Top