CS 101
Computer Programming and Utilization
Variable-Length Data Structures
Suyash P. Awate
Variable-Size Entities
• Motivation: in many programs:
1. Size of array is unknown at compile time.
e.g., involving arrays of floating-point numbers;
e.g., involving strings storing names
(Jet Li vs. Arnold Schwarzenegger)
2. Size of the data structure changes with time.
e.g., queue, library database
• We want to:
1. Allocate only as much memory as is necessary
2. De-allocate memory when not needed
• C++ program can allocate, and de-allocate,
memory outside activation frame (call stack)
• This memory region is called “heap”
Variable-Size Entities
• “Request” memory from heap using “new” keyword/operator
• Format: For data type T, “new T” requests allocation of memory from heap
• If request is granted (by operating system),
then expression “new T” evaluates to address of newly allocated memory,
else expression evaluates to NULL (indicating request failed)
• In general: “new call-to-a-constructor-for-T”
(allocate memory + call constructor)
• Example
• “T * q = new T[n];” allocates heap memory to
store an array of n elements of type T (‘n’ determined at run time)
• “Book * p = new Book;”
allocates heap memory for struct, calls constructor,
allocates pointer variable p, stores address of struct in p
Variable-Size Entities
• Example
Variable-Size Entities
• Memory
Leak
Variable-Size Entities
• Static binding and dynamic binding
• If we do: “float a[20];”,
then definition of ‘a’ à static (compile-time) binding
• Recall: array name is a constant pointer (cannot be reassigned)
• If we do “float * p = new float[20];”,
then definition of ‘p’ à dynamic (run-time) binding,
but where ‘p’ can be reassigned
• If we do: “float * const q = new float[20];”
then definition of ‘q’ à dynamic (run-time) binding,
but, because of “const” keyword, ‘q’ cannot be reassigned
Variable-Size Entities
• Memory de-allocation
• Explicitly free memory when no longer needed, using “delete” operator:
“delete p;” for non-array data structures
“delete[] q;” for array of data structures
• Good practice:
As soon as you execute “delete[] q;”,
let the next statement either set q to NULL (“q = NULL”)
or set q to point to another valid object (e.g., q = new … , or q = &obj)
• Until then ‘q’ is dangling/wild pointer
= pointer variable that doesn’t point to
valid object of appropriate type,
e.g., unallocated memory
• “Dangling” = unconnected
• “Wild” = unpredictable
Variable-Size Entities
• Using
dynamic
arrays
Standard Library
• Programming languages provide a lot of functionality relating to
algorithms that are used very very often
• Carefully written code with respect to
minimizing bugs,
efficiency of computation,
efficiency of memory usage,
modularity,
etc.
• Shared through header files
• C standard library
• [Link]/wiki/C_standard_library
• C++ standard library
• [Link]/wiki/C++_Standard_Library
Standard Library
• String class
• #include <string>
• Use this to handle text data instead of char arrays
• Handles memory management in a way that is transparent to programmer
Standard Library
• String class
• Comparing strings (based on lexicographic ordering)
• Operators ==, <, > are defined
• Can use expressions like: p == q, p < q, p >= q, etc.
• Strings can be passed to functions
• String elements. Sub-strings.
Standard Library
• String class
• Searching within a string
• If string not found, then find() returns a constant “string::npos”
• npos is a constant static member value with
greatest possible value for an element of type size_t (npos = “no position”)
Standard Library
• Template class “vector”
• #include <vector>
• Creation: empty
• Creation: with elements
• Accessing elements
• Append elements to end of vector (changes size)
• Remove elements from end of vector (changes size)
• We can insert and remove elements at any position from a vector (later)
• Vector automatically adjusts and tracks its size: [Link]() will return 11
Standard Library
• Template class “vector”
• Can also change size
• Call with newValue changes size, and
if newSize is greater, then new elements replaced with newValue
• Unlike arrays, you can assign one vector to another, e.g., “v = w;”
• Instead of using [] operator to access array elements,
vector class provides .at() function to access elements with bounds checking
• If index is outside bounds, program gives error message and halts
Standard Library
• Template class “vector”
• Vector variables can be passed as arguments to functions,
either by value or by reference
Standard Library
• Template class “vector”
• Vectors of user-defined data types
(e.g., structs)
• Vectors of pointers
• Multidimensional vectors
• A vector of vectors
• Can modify entire rows at once
• Such a datatype allows “rows” if varying lengths
Standard Library
• Template class “vector”
• A matrix class created as
a multidimensional vector;
Enforcing all rows
to be of same length
Standard Library
• Template class “vector”
• Sorting a vector
• #include <algorithm>
• [Link]() = first element of vector
• [Link]() = last element of vector
• If v is non-standard user-defined struct (e.g., student record, book record),
we must specify a way to compare elements of v
that can be used by sort()
1. Can define an overloaded operator<, which sort will use implicitly
2. Can define a non-member function, which can be passed to sort explicitly
Standard Library
• Template class “vector”
• Sorting
a vector
Standard Library
• Template class “vector”
• Sorting students by marks
• Can have another function to sort by roll number, if desired
Standard Library
• Iterators
• Vector class is a “container”, because it is designed to hold multiple elements
• In some ways, also the string class
• Standard library allows a common way to iterate over elements of a container,
using the “iterator”; its coding is also made highly computationally efficient
• Iterator is like a generalized pointer to an element of container
• Just as
we could have
the following
for an array …
• … we have
the following
for a container:
Standard Library
• Iterators
• Template class “vector”
• We can add and remove elements at any position from a vector
Practice Examples for Lab: Set 16
•1
Practice Examples for Lab: Set 16
•2
•3
•4
•5
Practice Examples for Lab: Set 16
•6