Template Classes and Vectors | Data Structures | CSCI 1200, Exams of Data Structures and Algorithms

Material Type: Exam; Class: DATA STRUCTURES; Subject: Computer Science; University: Rensselaer Polytechnic Institute; Term: Spring 2006;

Typology: Exams

Pre 2010

Uploaded on 08/09/2009

koofers-user-ve6
koofers-user-ve6 🇺🇸

10 documents

1 / 6

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
CSCI-1200 Computer Science II Spring 2006
Lecture 18 Templated Classes and Vectors
Test 3 General Information
Test 3 will be held Tuesday, April 11th, 2006 10-11:50am, West Hall Auditorium. No make-ups will
be given except for emergency situations, and even then a written excuse from the Dean of Students office will
be required.
Coverage: Lectures 1-19, Labs 1-10, HW 1-7.
Closed-book and closed-notes except for 1 sheet of 8.5x11 inch paper (front & back) that may be handwritten
or printed. Computers, cell-phones, palm pilots, calculators, PDAs, etc. are not permitted and must be turned
off.
All students must bring their Rensselaer photo ID card.
Practice problems are available on the course website. An optional review session will be held on Sunday
April 9th, from 7-9pm in DCC 324. Bring your questions!
Review from Lecture 17
Arrays and pointers
Different types of memory (“automatic”, static, dynamic)
Dynamic allocation of arrays
18.1 Today’s Lecture
Designing our own container classes:
Mimic the interface of standard library containers
Study the design of memory management code and iterators.
Move toward eventually designing our own, more sophisticated classes.
Vector implementation
Templated classes
Copy constructors, assignment operators and destructors
18.2 Vector Public Interface
In creating our own version of the vector class, we will start by considering the public interface:
public:
// Member functions and other operators
T& operator[] (size_type i);
const T& operator[] (size_type i) const;
void push_back(const T& t);
void clear();
bool empty() const;
iterator erase(iterator p);
size_type size() const;
void resize(size_type n);
public:
// Iterator operations
iterator begin();
const_iterator begin() const;
iterator end();
const_iterator end();
This appears to be quite simple and in fact it is. We will focus on each piece, but especially on the use of
templates, on the underlying representation, and on memory management.
pf3
pf4
pf5

Partial preview of the text

Download Template Classes and Vectors | Data Structures | CSCI 1200 and more Exams Data Structures and Algorithms in PDF only on Docsity!

CSCI-1200 Computer Science II — Spring 2006

Lecture 18 — Templated Classes and Vectors

Test 3 — General Information

  • Test 3 will be heldbe given except for emergency situations, and even then a written excuse from the Dean of Students office will Tuesday, April 11th, 2006 10-11:50am, West Hall Auditorium. No make-ups will

be required.

  • Coverage: Lectures 1-19, Labs 1-10, HW 1-7.
  • Closed-book and closed-notesor printed. Computers, cell-phones, palm pilots, calculators, PDAs, etc. are not permitted and must be turned except for 1 sheet of 8.5x11 inch paper (front & back) that may be handwritten

off.

  • All students must bring their Rensselaer photo ID card.
  • Practice problems are available on the course website.April 9th, from 7-9pm in DCC 324. Bring your questions! An optional review session will be held on Sunday

Review from Lecture 17

  • Arrays and pointers
  • Different types of memory (“automatic”, static, dynamic)
  • Dynamic allocation of arrays

18.1 Today’s Lecture

  • Designing our own container classes:
    • – Mimic the interface of standard library containersStudy the design of memory management code and iterators.
    • Move toward eventually designing our own, more sophisticated classes.
  • Vector implementation
  • Templated classes
  • Copy constructors, assignment operators and destructors

18.2 Vector Public Interface

  • In creating our own version of the vector class, we will start by considering the public interface:
public:// Member functions and other operators
T& operator[] (size_type i);const T& operator[] (size_type i) const;
void push_back(const T& t);void clear();
bool empty() const;iterator erase(iterator p);
size_type size() const;void resize(size_type n);
public:// Iterator operations
iterator begin();const_iterator begin() const;
iterator end();const_iterator end();
  • This appears to be quite simple and in fact it is.templates, on the underlying representation, and on memory management. We will focus on each piece, but especially on the use of

18.3 Templated Class Declarations and Member Function Definitions

  • In terms of just the layout of the code in templated class. The keyword template and the template type name must appear before the class declaration, vec.h (last page of handout), the biggest difference is that this is a

e.g., template class Vec

  • Within the class declaration, T”. In the actual text of the code files, templated member functions are often defined (written) T is used as a type and all member functions are said to be “templated over type inside the class

declaration.

  • The templated functions defined outside the template class declaration must be preceeded by the phrase: template and then when Vec is referred to it must be as Vec. For example, for member

function create (two versions), we write:

template void Vec::create

18.4 Syntax and Compilation

  • Templated classes and templated member functions are not created/compiled/instantiated until they areneeded. Compilation of the class declaration is triggered by a line of the form: Vec v1; with int

replacingfunctions are not compiled unless they are used. T. This also compiles the default constructor for Vec because it is used here. Other member

  • When a different type is used withdeclaration is compiled again, this time with Vec, for example in the declaration: double replacing T instead of Vec z; int. Again, however, only the the template class

member functions used are compiled.

  • This is very different from ordinary classes, which are usually compiled separately and all functions are compiledregardless of whether or not they are needed.
  • The templated class declaration and the code for all used member functions must be provided where theyare used. As a result, member functions definitions are often included within the class declaration or defined

outside of the class delaration but still in the .cpp file, this file must be #include-d, just like the .h file. If member function definitions are placed in a separate .h file, because the compiler needs to see it in order to

generate code.Note: Including function definitions in the .h for ordinary non-templated classes may lead to compilation errors

about functions being “multiply defined”. Some of you have already seen these errors.

18.5 Member Variables

Now, looking inside the Vec class at the member variables:

  • m datapointers and arrays. is a pointer to the start of the array (after it has been allocated). Recall the close relationship between
  • m size member function should return, indicates the number of locations currently in use in the vector. This is exactly what the size()
  • m alloc is the total number of slots in the dynamically allocated block of memory.

Drawing a picture, which we will do in class, will help clarify this, especially the distinction between m alloc. m size and

18.6 Typedefs, Iterators and Pointers

  • Several types are created throughare used as ordinary class type names. For exmaple typedef statements in the first Vec::iterator public area of is an iterator type defined by the Vec. Once created the names

VecAlso, Vec::size type class. It is just a T * is the size type, defined here as an. unsigned int.

  • Thus, internal to the declarations and member functions, T* and iterator may be used interchangeably.
  • Also, the ++ and -- operators on pointers automatically apply to iterators.

18.11 Copy Constructor

  • This constructor must dynamically allocate any memory needed for the object being constructed, copy thecontents of the memory of the passed object to this new memory, and set the values of the various member

variables appropriately.

  • In our Vec class, the actual copying is done in a private member function called copy.

18.12 Exercise: Write the private member function copy

// Create the vector as a copy of the given vector.template
void Vec::copy(const Vec& v) {

18.13 Aside (1): the “this” pointer

  • All class objects have a special pointer defined calledit may not be changed. this which simply points to the current class object, and
  • The expression *this is a reference to the class object.
  • The this pointer is used in several ways:
    • – Make it clear when member variables of the current object are being used.Check to see when an assignment is self-referencing.
    • Return a reference to the current object.

18.14 Aside (2): Assignment operators, generally speaking

  • Assignment operators of the form: are translated by the compiler as: v1.operator=(v2);v1 = v2;
  • Cascaded assignment operators of the form: are translated by the compiler as: v1.operator=(v2.operator=(v3)); v1 = v2 = v3;
  • Therefore, the value of the assignment operator (operator. This in turn means the result of an assignment operator ought to be a reference to an object.v2 = v3) must be suitable for input to a second assignment

18.15 Assignment operator for Vec

  • The implementation of an assignment operator usually takes on the same form for every class:
    • – Do no real work if there is a self-assignment.Otherwise, destroy the contents of the current object then copy the passed object, just as done by the
    • copy constructor.Return a reference to the (copied) current object, using the this pointer.

18.16 Destructor

  • Called implicitly when an automatic object goes out of scope or a dynamic object is deleted. It can never becalled explicitly!
  • Must delete the dynamic memory “owned” by the class.
  • The syntax of the function definition is a bit weird. The ~ has been used as a logic negation in other contexts.

18.17 Increasing the Size of the Vec

  • push_back(T const& x)allocated array is full (m size == m alloc adds to the end of the array, increasing)? m size by one T location. But what if the

1. Allocate a new, larger array. The best strategy is generally to double the size of the current array. Why?2. If the array size was originally 0, doubling does nothing. We must be sure that the resulting size is at

3. Then we need to copy the contents of the current array.least 1.

4. Finally, we must delete current array, make theadjust the m size and m alloc variables appropriately. m data pointer point to the start of the new array, and

  • Only when we are sure there is enough room in the array should we a ctually add the new object to the backof the array.
  • Finish the definition of Vec::push back:
// Add an element to the end, resize if necesssary.template void Vec::push_back(const T& val) {
if (m_size == m_alloc) {// Allocate a larger array, and copy the old values
}// Add the value at the last location and increment the bound
m_data[m_size] = val;++ m_size;

18.18 // Shift each entry of the array after the iterator. Return the iterator, Exercise: Write the Vec::erase and Vec::resize functions

// which will have the same value, but point to a different location.template typename Vec::iterator Vec::erase(iterator p) {
// If n is less than or equal to the current size, just change the size.// greater than the current size, the new slots must be filled in with the given value. If n is
// Re-allocation should occur only if necessary.template void Vec::resize(size_type n, const T& fill_in_value) { push_back should not be used.