In this tutorial you will learn the basics of C++ and how to use lists and maps. This will allow you to write a simple C++ program that you will then compile. The program will be a Visual Studio console application
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.
Experience using a contemporary OO language such as Java or C# would be useful but is not required.
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
Not what you are looking? Try the next tutorial – Inheritance
Lab 1: Using list
Lab 1: Using list
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
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
...
}
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;
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
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.
}
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
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();
}
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
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.
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"];
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
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;
}
}
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);
}
}
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);
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.
Manage cookie consent
You can view this website without consenting to extra cookies. However you will need to accept the 'marketing' cookies to send messages via the contact forms & see any maps displayed on the site
Functional
Always active
Cookies necessary for the website to work.
Preferences
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
Statistics
The technical storage or access that is used exclusively for statistical purposes.Cookies used to track user interaction on the site, which helps us to evaluate & improve the website.
Marketing: Forms & additional content (Marketing)
We need your permission to place ‘marketing’ cookies, so you are able to use the contact forms & see embedded content e.g. videos and maps. - - - - We have added protection to our contact forms to help prove that a human (rather than a spambot) is filling
If you would like to see more content like this in the future, please fill-in our quick survey.