Wednesday, February 19, 2003

In order to improve performance of the vector solutions that we saw in the previous class, we can use a list container. Here is the main() program:


#include <algorithm>
#include <list>
#include <string>

#include "grade.h"
#include "Student_info.h"

using std::max;

using std::cin;
using std::cout;
using std::endl;
using std::list;
using std::string;

list<Student_info> extract_fails(list<Student_info>& v);

int main()
{
        list<Student_info> vs;
        Student_info s;
        string::size_type maxlen = 0;
        while (read(cin, s)) {
                maxlen = max(maxlen, s.name.size());
                vs.push_back(s);
        }

        vs.sort(compare);

	list<Student_info> fails = extract_fails(vs);

	list<Student_info>::iterator i;

	for (i = fails.begin(); i != fails.end(); ++i)
		cout << i->name << " " << grade(*i) << endl;

	return 0;
}


And here is the implementation of the extract_fails() function using the list container. Note that its implementation is identical to the vector version that used iterators, except that vector has been replaced by list.


#include <list>
#include "Student_info.h"
#include "grade.h"

using std::list;
// version 4: use `list' instead of `vector'
list<Student_info> extract_fails(list<Student_info>& students)
{
	list<Student_info> fail;
	list<Student_info>::iterator iter = students.begin();

	while (iter != students.end()) {
		if (fgrade(*iter)) {
			fail.push_back(*iter);
			iter = students.erase(iter);
		} else
			++iter;
	}
	return fail;
}



Advantages of list containers

Disadvantages of list containers

Advantages of vector containers

Disadvantages of vector containers

Miscellaneoues

Although we will not be covering K&M § 5.6, 5.7, 5.8 in class, you should sill read these sections as they continue to give further examples of container manipulation. Note that instead of doubles, string are actually stored in the vector container.

There are a couple of interesting functions methods introduced in these sections.

Last modified: Thu Feb 20 13:00:54 2003