Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Standard Template Library (STL) in C++: Lab 10, Lab Reports of Software Engineering

A lab assignment for cs032 2009 that introduces the standard template library (stl) in c++, specifically the list, map, and deque container classes. It also covers iterators, algorithms, and creating a c++ class using stl structures. The lab requires students to implement a gradesdatabase class to manage student data and grades.

Typology: Lab Reports

Pre 2010

Uploaded on 08/16/2009

koofers-user-72k
koofers-user-72k 🇺🇸

10 documents

1 / 7

Toggle sidebar

Related documents


Partial preview of the text

Download Standard Template Library (STL) in C++: Lab 10 and more Lab Reports Software Engineering in PDF only on Docsity! CS032 2009 Lab 10 Standard Template Library Introduction Last week, we discussed using system calls, the lowest useable level of code available. Obviously you could write in Assembly if you wanted. Hell, you could even use a magnifying glass, a magnetized needle, and a very steady hand1, but that would be stupid. Regardless, just because you know how to manipulate the system doesn’t mean you have to prove it at every available opportunity. In all honesty, someone out there is probably a more leet haxor and has implemented your desired data structure better than you ever could. It’s a better idea to just swallow your pride and use his2 version. This week, we’ll be doing exactly that. The Standard Template Library (STL) is a C++ library which gives you access to all of the most common data structures and algorithms. In this lab we’ll cover three useful container classes from the STL: list, map, and deque. SGI has excellent documentation available on the STL. Keep it bookmarked and refer to it forever: http://www.sgi.com/tech/stl/ It’s important enough to mention again, even though you just saw it! http://www.sgi.com/tech/stl/ We won’t tell you everything you need to know. You will need to look at this documentation for the specifics on how to use the STL! http://www.sgi.com/tech/stl/ The T in STL comes from the fact that most objects in the library are C++ templates. A template behaves just like an object except that it can be parameterized by type, which is a fancy way for saying that you can specify what types are used internally to the object from outside of the object. Examples: list < People > is a list of People objects; list < double > is a list of doubles; map < int, string > is a map with integer keys and string values. This can be done because a container can be easily ignorant of what you put into it, so you can use the same code and just parameterize what types it will operate on. Java does this now, but back in the dark ages of pre 1.5, containers could only hold things that of type Object. Also, the compiler couldn’t give you any help on determining what type you’d get out of the Java containers, so you had to cast them yourself and hope you got it right. With templates you can do true compile-time type checking, which is a good thing3 Template objects take, as parameters, the types that they are going to use, inside the < and > symbols. By using templates, the STL allows you to use a single list class to create a list of People or a list of Recipes or a list of Lists. Containers • List An STL list is a doubly-linked list, supporting both forward and backward traversal. std::list < type> myList; 1. This is a linked list, so everything you remember from CS 16, CS 18 or CS 19 will apply. It’s great for iterating forwards and backwards and for constant time manipulation( inserting and deleting ), but accessing an arbitrary element will take linear time. 2. Singly linked lists are known as slists and may be more efficient if you only need to go in one direction. 1http://xkcd.com/378 2Probably his, not hers, let’s be real for a minute 3Note that Java’s generics in versions 1.5 and later are comparable to, but not exactly like, templates. Take CS173 to learn more about the differences. 1 • Map A map is implemented as a red-black tree(though you’ve probably forgotten how they’re implemented) that stores and sorts data by separate key values. You can think of it as an array that you can index with anything. std::map < key type, data type> myMap; 1. Each key value can only be associated with a single datum. If you’d like to have multiple data per key use a multimap. 2. To get something out, use the find function. More on this when we get to iterators. You can also use subscripting (foo = myMap[3];) to access data, but if there is no datum for the key you subscript with one will be created for you, and you might not want that. Keep it in mind. 3. Insertion into a map is done with subscripting: myMap[3] = foo; will put the data from the variable foo into the map for the key 3. This will overwrite any entry that’s already there for that key, so make sure that’s what you want to do4. 4. You can choose how your map sorts its keys by adding an optional comparator to the template arguments (right after the required data type). It defaults to less < key type >, but others (like greater) are available and you can write your own. Comparators are an excellent example of the power and flexibility of templates. http://www.sgi.com/tech/stl/Map.html • Deque5 A deque is a Double-Ended QUEue that supports constant time insertion at the beginning and end of the sequence, and constant time access of elements. Use it when you might have used a vector or an array in another language. std::deque < type> myDeq; 1. Befitting their name, deques have push back(type ) , pop back(type ) and other functions that make them very stack or queue-like. 2. They also support vector-like behavior, unlike lists, such as constant-time random access of elements using subscripting. foo = myDeq[0]; sets foo to the value of the first element of the deque. Be warned that subscripting is not range checked for deques, and if you try to access more elements than exist in your deque, your program may encounter a segmentation fault. http://www.sgi.com/tech/stl/Deque.html Iterators An iterator is an abstraction of the pointer to an individual item within the data structure. For example, if you are using a deque of strings, a deque iterator represents a pointer to one string within the deque. An iterator for our deque of strings is defined as follows: deque < string > :: iterator myIter; Iterators are useful for access and traversing through your data structures. The following is sample code on how to use an iterator to run through a deque of strings6: // define in header to avoid writing out template syntax each time typedef std::deque< std::string > StringDeque; typedef StringDeque::iterator StringDequeIterator; 4This is especially important if your map is storing pointers to objects as data. Replacing a pointer in the map will not change the memory that that pointer pointed to, nor will it delete that memory. 5Pronounce it “deck” 6It might not make a tangible difference to you, but algorithmically, it’s probably better to use the pre-increment operator ++var rather than the post-increment operator var++, since the compiler will not have to make a temporary copy of the object for the iteration. 2 Exercises 1. We have filled in addStudent, printStudent, overwriteGrade, and printGradesByStudent to give you examples of how to work with stl iterators and functions. 2. Fill in the list methods: removeStudent, addAssignment, removeAssignment and printAssignments. (HINT: some of these are VERY similar to the TA provided code) Checkpoint 1: Show your lab TA the code for your list methods. TA Initials: (40 pts) 3. Fill in {set,get}Grade and doesGradeExist. You should now be using a map, as described above. 4. Now that we have grades, we need to change removeStudent and removeAssignment to remove the grades for that student/assignment. Change the methods to do this. Checkpoint 2: Show your lab TA the code for your grade methods and the updated removes. TA Initials: (20 pts) 5. Finally, fill in the display methods: printGradesByAssignment, getFinalGrade and getAssignmentSum- mary. getFinalGrade should calculate the average of all of a student’s assignment grades, giving them a 0 for any assignment they do not have a grade for. getAssignmentSummary should also calculate the average (do NOT give missing students 0’s here), as well as the standard deviation. For anyone who hasn’t taken statistics, the standard deviation is:√√√√ 1 n− 1 n∑ i=1 (xi − x̄)2 Where the xi’s are our numbers, and x̄ is their average. Checkpoint 3: Show your lab TA the code for the entire database. TA Initials: (40pts) 5 C++ Appendix 1. Creating a C++ class If you look in grades.H, you will see a definition of the class GradesDatabase: using namespace std; \\All the files in the C++ standard library declare all of its functions within the std namespace. We include this statement so that we can use cout and cin, functions of the iosteam to print out our values to the terminal. class GradesDatabase { public: \\public methods and variables go here GradesDatabase(); \\constructor ~GradesDatabase(); \\destructor void printStudents(); \\public void method int addStudent(const string* stud); \\public method that returns an integer int removeStudent(const string* stud); ... private: \\private methods + variables go here map<pair<string, string>, double> gradeMap; \\instance variable gradeMap of type map list<string> studentList; list<string> assignmentList; }; // semi-colon ends the definition Note that the .H file only creates the definition of the class. You need to then fill in all the methods inside the corresponding .C class. 2. Defining methods Note the headers for the methods in the grades.C file: int GradesDatabase::removeStudent(const string* stud) { } The scope operator :: is used when declaring methods. I have a class called GradesDatabase and it has a method called removeStudent, when defining the function in the .C file, I call it GradesDatabase::removeStudent(). The scope operator is needed because a .C file could contain method definitions for multiple classes, so we need to know for which class each method is being defined. Note that we don’t need to name our .C file or our .H after the class, as in GradesDatabase.H/C. Though we would advise you to seperate your classes into seperate .C and .H files when writing complex projects. 3. Constructor/Destructor The constructor and destructor methods look like this in C++: \* constructor *\ GradesDatabase::GradesDatabase() { } 6 \* destructor *\ GradesDatabase::~GradesDatabase() { /* clears the STL structures */ studentList.clear(); assignmentList.clear(); gradeMap.clear(); } The constructor method name is the same as the name of the class, this is very similar to Java and is automatically called when the class is initialized. To initialize an object from the heap, you need to use new: GradesDatabase *gradesDB = new GradesDatabase(); The destructor is implied in Java (though you can write one yourself). In C++, since we don’t have a garbage collector, the classes that are initialized need to be deleted. When they are deleted, the deconstructor is called. The deconstructor should contain all the cleanup code, ex: free all the memory that the class initialized for classes and structures. In our class, we simply clear our STL lists and map. You can delete a class with delete: delete gradeDB; Every class that is allocated with a new should be deallocated with a delete. This similar to C where you need to free for every malloc. You can also initialize the class on the stack as we do in main.C: GradesDatabase db; This makes the db a local variable in main, but since main won’t exit till the program exits, we don’t need to worry about this object going away, we also don’t need to delete it. Be very careful when allocating objects on the stack, usually reserve this practice for objects initialized in main(). 7
Docsity logo



Copyright © 2024 Ladybird Srl - Via Leonardo da Vinci 16, 10126, Torino, Italy - VAT 10816460017 - All rights reserved