Dynamic Data Structures II Lecture Notes PDF
Document Details
Uploaded by FervidDune
ETH Zurich
Tags
Summary
These lecture notes cover dynamic data structures, specifically focusing on vectors and pointer arithmetic in C++. The notes provide a recap, introduce custom vector implementation, explore vector memory layouts, and explain pointer arithmetic and access operations with relevant examples. Focuses on concepts and code examples, not a past paper.
Full Transcript
22. Dynamic Data Structures II 579 Recap: vector Can be initialised with arbitrary size n Supports various operations: e = v [ i ]; // Get element v[i] = e; // Set element l = v. size (); // Get size v. push_back ( e );...
22. Dynamic Data Structures II 579 Recap: vector Can be initialised with arbitrary size n Supports various operations: e = v [ i ]; // Get element v[i] = e; // Set element l = v. size (); // Get size v. push_back ( e ); // Append element... A vector is a dynamic data structure, whose size may change at runtime 580 Our Own Vector! We’ll implement our own vector: our_vector 581 Vectors in Memory Already known: A vector has a contiguous memory layout Question: How to allocate a chunk of memory of arbitrary size during runtime, i.e. dynamically? 582 new for Arrays underlying type new T[expr] new-Operator positive integer value, value n Effect: new contiguous chunk of memory n elements of type T is allocated This chunk of memory is called an array (of length n) 583 new for Arrays underlying type p = new T[expr] new-Operator positive integer value, value n Value: the starting address of the memory chunk p Type: A pointer T * 584 Pointer Arithmetic: Pointer plus int T * p = new T [n]; // p points to first array element p p+3 p+n Question: How to point to rear elements? → via Pointer arithmetic: p yields the address of the first array element, *p its value *(p + i) yields the value of the ith array element, for 0 ≤ i < n *p is equivalent to *(p + 0) 585 Pointer Arithmetic: Pointer plus int int* p0 = new int{1,2,3,4,5,6,7}; // p0 points to 1st element int* p3 = p0 + 3; // p3 points to 4th element *(p3 + 2) = 600; // set value of 6th element to 600 std::cout