Uploaded by ddikibo2004

maps.cpp

advertisement
12/16/22, 4:35 PM
maps.cpp
/* maps.cpp
B. Bird - 2022-01-03
*/
#include <iostream>
#include <map>
#include <string>
int main(){
// std::map is an associative array, and is parameterized
// by two types, a "key type" and a "value type".
// The student_names object maps strings to strings
std::map< std::string, std::string > student_names {};
// To add a (key, value) pair to a map, the square bracket
// operator can be used. If the provided key is not found,
// it is added.
student_names["V00123456"]
student_names["V00123457"]
student_names["V00654322"]
student_names["V00654321"]
=
=
=
=
"Alastair Avocado";
"Rebecca Raspberry";
"Hannah Hindbaer";
"Meredith Malina";
// The exam_grades object maps strings (student IDs)
// to ints (grades)
std::map< std::string, int > exam_grades {};
exam_grades["V00123456"]
exam_grades["V00123457"]
exam_grades["V00654322"]
exam_grades["V00654321"]
=
=
=
=
63;
91;
87;
87;
// The value associated with any key can be retrieved
// using the square bracket operator or the .at() function.
// Task 1: Print out the name and grade of the student with
//
Student ID "V00654322"
std::cout
std::cout
std::cout
std::cout
//
//
//
//
//
<<
<<
<<
<<
"The student with ID V00654322 is named ";
student_names["V00654322"] << " and got ";
exam_grades["V00654322"] << " on the exam";
std::endl;
Entries in a map can be changed as needed (equivalent
to a regular array or vector).
Like vectors, maps have the .at function, which is similar
to the square brackets but does not automatically
create the key.
// Task 2: Alter the grade associated with V00654322
//
to the value 89.
std::cout << "Changing V00654322's grade is what doe?" << std::endl;
exam_grades.at("V00654322") = 32;
// Repeat
std::cout
std::cout
std::cout
std::cout
Task 1 to print out the updated information.
<< "The student with ID V00654322 is named ";
<< student_names["V00654322"] << " and got ";
<< exam_grades["V00654322"] << " on the exam";
<< std::endl;
// Task 3: Use for-each loops to print out each map.
file:///Users/daviddikibo/Downloads/maps.cpp
1/2
12/16/22, 4:35 PM
//
//
maps.cpp
The first loop should print a list of IDs and names,
and the second loop should print IDs and grades.
//A for-each loop over a map will iterate over "pair" objects,
//which contain a key and value.
std::cout << "Student Names: " << std::endl;
for( auto P: student_names){
std::cout << P.first << " " << P.second << std::endl;
}
std::cout << "Exam Grades: " << std::endl;
for( auto P: exam_grades){
std::cout << P.first << " " << P.second << std::endl;
}
// Task 4: Print a single list of ID, name, grade (this
//
is a "join" operation).
std::cout << "Joined list: " << std::endl;
for( auto [id, name]: student_names ){
std::cout << id << " " << name << " " << exam_grades.at(id) << std::endl;
}
return 0;
}
file:///Users/daviddikibo/Downloads/maps.cpp
2/2
Download