federico-busato / Modern-CPP-Programming

Modern C++ Programming Course (C++03/11/14/17/20/23/26)
https://federico-busato.github.io/Modern-CPP-Programming/
11.91k stars 798 forks source link

Code fixes for "Implement a Custom Iterator" in 17.Iterators_Containers_Alg.pdf #77

Closed eugenefil closed 6 months ago

eugenefil commented 7 months ago

These are the fixes needed to make the whole piece compile and run.

p.44 "Implement a Simple Iterator":

 #include <iostream>
+#include <algorithm> // std::find

 // !! List implementation here

p.45 "Implement a Simple Iterator (List declaration)": replace head -> _head

-    It begin() { return It{head}; } // begin of the list
+    It begin() { return It{_head}; } // begin of the list
     It end() { return It{nullptr}; } // end of the list
 };

p.46 "Implement a Simple Iterator (List definition)": replace head -> head, tail -> _tail

 void List::push_back(const value_t& value) {
     auto new_node = new Node{value, nullptr};
-    if (head == nullptr) { // empty list
-        head = new_node; // head is updated
-        tail = head;
+    if (_head == nullptr) { // empty list
+        _head = new_node; // head is updated
+        _tail = _head;
         return;
     }
-    assert(tail != nullptr);
-    tail->_next = new_node; // add new node at the end
-    tail = new_node; // tail is updated
+    assert(_tail != nullptr);
+    _tail->_next = new_node; // add new node at the end
+    _tail = new_node; // tail is updated
 }

p.47 "Implement a Simple Iterator (Iterator declaration)": replace second parameter itA -> itB

         // Not equal -> stop traversing
-        friend bool operator!=(const It& itA, const It& itA);
+        friend bool operator!=(const It& itA, const It& itB);

         It& operator++(); // Pre-increment

p.48 "Implement a Simple Iterator (Iterator definition)":

  1. fix constructor
  2. replace _data -> _value in dereferencing operator
  3. everywhere replace It:: -> List::It:: for an out-of-line definition
    
    -void It::It(Node* ptr) :_ptr(ptr) {}
    +List::It::It(Node* ptr) : _ptr(ptr) {}

-value_t& It::operator() { return _ptr->_data; } +value_t& List::It::operator() { return _ptr->_value; }

-bool operator!=(const It& itA, const It& itB) { +bool operator!=(const List::It& itA, const List::It& itB) { return itA._ptr != itB._ptr; }

-It& It::operator++() { +List::It& List::It::operator++() { _ptr = _ptr->_next; return this; } -It It::operator++(int) { +List::It List::It::operator++(int) { auto tmp = this; ++(*this); return tmp; }

federico-busato commented 6 months ago

Thanks, @eugenefil!! you found so many typos and problems in this chapter

eugenefil commented 6 months ago

You're very welcome!