Implementing an iterator vs. looping over a list

I want to loop over a number of rows in a database and I have implemented an object in order to access the rows. Now when using this object I am not sure about the best practice. Implementing an iterator looks nice in the higher-level script but is somewhat unnecessary.

So I wondered, what are the benefits and disadvantages of looping over a list vs. a ‘proper’ iterator?

Alternatively, would either option make more sense if I changed the structure of my object?

Here is my code using python 2.7:

class process_scope(object):      __columns = ['id', 'type', 'start', 'end', 'seconds', \                         'static', 'table_ref']     def __init__(self, force = False):         self.force = force         self._load_timeframes()         self._reduce_timeframes()      def __iter__(self):         return self      def next(self):         try:             return self.timeframes.pop()         except IndexError:             raise StopIteration      def _load_timeframes(self):         self.timeframes = ((1, 'type_1', 000, 999, 999, 0, 'table_1'),                            (2, 'type_2', 000, 999, 999, 0, 'table_2'),                            (3, 'type_3', 000, 999, 999, 1, 'table_3'),                            (4, 'type_2', 000, 999, 999, 0, 'table_4'),                            (5, 'type_1', 000, 999, 999, 0, 'table_5'))      def _reduce_timeframes(self):         relevant_timeframes = []         for tf in self.timeframes:             tf = dict(zip(process_scope.__columns, tf))             if tf['static'] == 0 or self.force:                 relevant_timeframes.append(tf)          self.timeframes = relevant_timeframes 

Here is the usage option utilizing the iterator…:

for i in process_scope():     print i 

…and the option without implementing the iterator:

iter_ = process_scope().timeframes for i in iter_:     print i 

Rust Iterator that correlates a slice with itself

In my effort to learn Rust I’ve tried implementing an Iterator that splits up a buffer in two halves, and correlates both halves by sliding them over each other with different positions (lags). You could use this e.g. to do autocorrelation, given a correlation function between two buffers (dot product for example).

I’m fairly new to Rust (coming from a C++ background), so any and all advice is welcome. Specifically to lifetimes, generics and idiomatic usage of Rust.

Also, should I turn this into an iterator adapter that takes an iterator and collects the data in an internal Vec? Would that cover a wider array of input?

pub struct Slide<'a, T, F> {     items: &'a [T],     func: F,     lag: usize, }  impl<'a, T, F> Slide<'a, T, F> {     pub fn new<Out>(items: &'a [T], func: F) -> Slide<'a, T, F>     where         F: Fn(&'a [T], &'a [T]) -> Out,     {         Slide {             items,             func,             lag: 0,         }     } }  impl<'a, T, F, Out> Iterator for Slide<'a, T, F> where     F: Fn(&[T], &[T]) -> Out, {     type Item = Out;      fn next(&mut self) -> Option<Out> {         let half_length = self.items.len() / 2;          if self.lag < half_length {             let y = (self.func)(                 &self.items[0..half_length],                 &self.items[self.lag..self.lag + half_length],             );              self.lag += 1;             Some(y)         } else {             None         }     } } ``` 

Metodos Iterator

Como sumar todos los objetos de un arraylist con iterator: esta parte me funciona correctamente

public class Uso_2cIterator {   public static void main(String[] args) {        Scanner sc=new Scanner(;       int num;       Integer suma=0;       int media;       int cont=-1;        ArrayList<Integer> miAdeNumeros=new ArrayList<>();        do{       System.out.print("Introduce nº enteros, para terminar escribe 0 (cero) " + "\nNumero: ");       num=sc.nextInt();        if(num!=0){       miAdeNumeros.add(num); cont++;}       }       while(num!=0);         System.out.println("Contenido del ArrayList " + miAdeNumeros);        Iterator it=miAdeNumeros.iterator();       while(it.hasNext()){         //  System.out.print(" " +" "); 

El problema esta aqui no se que poner entre los parentesis para darle 1 posicion diferente cada vez, si fuese un bucle for le pondria i y listo pero no se como hacerlo con iterator

suma+=miAdeNumeros.get(0);       }        System.out.println("La suma total es: " +suma);          media=suma/miAdeNumeros.size();        System.out.println("La media total es: " +media);   }} 

C++ linked list iterator implementation

I’m a first year computer engineering student and would appreciate feedback on some code.

I’ve created a linked-list with an iterator to be able to range for loops like: for (int i : list) {} where list is Linked_List<int> list;.

Flaws I already know of but choose to ignore because of how the teacher in class implements stuff:

  • Use of raw pointers


namespace Util {     template<typename T>     class Linked_List     {     public:         struct Iterator;     private:         struct Node;     public:         Linked_List();         ~Linked_List() noexcept(false);         Linked_List(const Linked_List&) = delete;         Linked_List(Linked_List&&) = delete;         Linked_List& operator=(const Linked_List&) = delete;         Linked_List& operator=(Linked_List&&) = delete;          // Modifiers         void push_back(T);         void push_front(T);         void pop_back();         void pop_front();          // Capacity         bool empty() const;         unsigned int size() const;          // Element access         T back() const;         T front() const;         Iterator begin() const;         Iterator end() const;          // TODO:         //void insert(Iterator, T);         //void erase(Iterator);         //void swap(T, T);     private:         Node* _head;         Node* _tail;         unsigned int _size;     }; }; 


#include "pch.h" #include "Linked_List.h"  namespace Util {     template<typename T>     struct Linked_List<T>::Node     {         Node() : prev(nullptr), next(nullptr) {}         Node(T t) : value(t), prev(nullptr), next(nullptr) {}         Node* prev;         Node* next;         T value;     };      template<typename T>     struct Linked_List<T>::Iterator     {         Iterator() : _current(nullptr)         {             //         }         T& operator*() const         {             return _current->value;         }         Iterator& operator++()         {             _current = _current->next;             return *this;         }         bool operator!=(const Iterator& rhs)         {             return _current != rhs._current;         }     private:         friend class Linked_List<T>;         Iterator(Node* n) : _current(n) {}         Node* _current;     };      template<typename T>     Linked_List<T>::Linked_List() : _size(0)     {         _head = new Node();         _tail = new Node();         _head->next = _tail;         _tail->prev = _head;     }      template<typename T>     Linked_List<T>::~Linked_List() noexcept(false)     {         while (!empty())         {             pop_back();         }     }      template<typename T>     void Linked_List<T>::push_back(T t)     {         Node* n = new Node(t);         n->prev = _tail->prev;         n->next = _tail;         _tail->prev->next = n;         _tail->prev = n;         ++_size;     }      template<typename T>     void Linked_List<T>::push_front(T t)     {         Node* n = new Node(t);         n->next = _head->next;         n->prev = _head;         _head->next->prev = n;         _head->next = n;         ++_size;     }      template<typename T>     void Linked_List<T>::pop_back()     {         if (empty()) throw Error("pop_back(): on empty list");         Node* n = _tail->prev;         _tail->prev->prev->next = _tail;         _tail->prev = _tail->prev->prev;         --_size;         delete n;     }      template<typename T>     void Linked_List<T>::pop_front()     {         if (empty()) throw Error("pop_front(): on empty list");         Node* n = _head->next;         _head->next->next->prev = _head;         _head->next = _head->next->next;         --_size;         delete n;     }      template<typename T>     bool Linked_List<T>::empty() const     {         //return (_head->next == _tail) && (_tail->prev == _head);         return size() == 0;     }      template<typename T>     T Linked_List<T>::back() const     {         if (empty()) throw Error("back(): on empty list");         return _tail->prev->value;     }      template<typename T>     T Linked_List<T>::front() const     {         if (empty()) throw Error("front(): on empty list");         return _head->next->value;     }      template<typename T>     unsigned int Linked_List<T>::size() const     {         return _size;     }      template<typename T>     typename Linked_List<T>::Iterator Linked_List<T>::begin() const     {         return Iterator(_head->next);     }      template<typename T>     typename Linked_List<T>::Iterator Linked_List<T>::end() const     {         return Iterator(_tail);     } };  

Python 3.7 @dataclass __iter__ and __next___ my iterator wont stop looping. Not sure how to break/stop loop

So I have this code

@dataclass class myQuque: """ simple FIFO quque """ _container: list = field(init=False, default_factory=list) _iter : iter = field(init=False,default=None)  def __post_init__(self):     self._iter = self.__iter__()  def __iter__(self):     return iter(self._container)  def __next__(self):     return self._iter  def pop(self):     return self._container.pop()  def add(self, parm):     self._container.insert(0, parm) 

Then when I call a simple loop on an instance of the object Assuming y is a filled object. My iterator works (yea!) but it won’t stop looping (boo!) Not sure how (I think) make next terminate.

    for i in y:     print(i) 

How should I handle the risk of an iterator getting out of its vector?

I am coding a game boy disassembler in C++. The program (simplified here) converts a vector of byte into an assembly instruction and print it.

To do so, it iterates through the vector of bytes (char) with an iterator. I noticed that with the it!=char_vect.end() condition, there is the risk that the iterator goes out from the vector. So I have to check that I do not get out of the vector at each iteration and if it occurs, I throw an error.

#include <iostream> #include <vector>   int disassemble(std::vector<char>::iterator& it){      int opcode = *it;     int opbytes = 1; //number of bytes used by the operator      switch(opcode){         case 0x76 : std::cout<<"HALT "<<std::endl; opbytes = 1; break;         case 0x10 : std::cout<<"STOP $  "<<(int)*(it+1)<<std::endl; opbytes =2; break;          default : std::cout<<"Instruction not implemented yet"<<std::endl;     }      return opbytes; }  int main(){      std::vector<char> char_vect = {0x76, 0x10, 0x20}; // Fill vector of char     std::vector<char>::iterator it = char_vect.begin();      // First I only did that     //while (it!=char_vect.end()){     //  it+=disassemble(it);     //}      // But I have to check that I do not go out of the char_vect      while (it!=char_vect.end()){         try{             it+=disassemble(it);             //check that it do not overpass end             if (size_t(it - char_vect.begin())>char_vect.size()){                 throw "Try to disassemble instruction outside of memory bounds";             }         }         catch(const char * c){             std::cerr << "Fatal error: " << c << std::endl;             return 1;         }     }     return 1; } 

I chose to throw an error because for a valid input sequence of bytes (for example a valid rom file), and the opbytes variable set properly by disassemble(), this should not happend. So if it happens, it means that something is wrong so I want to know that. Am I right?

I feel like it is quite ugly to check that the iterator does not go out of bounds at each iteration, do you think I should rather use a vector index for iterating over the vector? Or handle this case in a different way than by throwing an error?

How much an iterator should do

I am working on creating iterators, for strings, lists, trees, graphs, and potentially other things.

First a side note.

I have a string data type in my engine. The string is implemented as a bunch of small chunks separated physically in memory, let’s say 256-byte chunks. So a single string might look like this in memory.

asdfasdfasd...256 [something else] [something else] fasdfasdfasdf 

So the final string would be:


However, when in code, I want to access the string like this:

string[10]  for (char in string) {   // ... } 

Basically, it feels like a simple array.

But when you access a character in string, it has to have some context. It needs to know which chunk we are currently on, the length of chunks, and if another chunk follows this current chunk. There’s a lot under the hood of for (char in string).

Given that, I was thinking of having an iterator implement this. But the first part of my confusion is how much should go into the iterator, vs. how much should go into some generic looper/api that takes the iterator as an argument.

For example.

iterator.iterate(function(item, index){  }) 

The iterator does everything. This would mean, if we were implementing “graph traversal”, there would be an entire graph traversal algorithm in the iterator, and it would take a graph as input. This would mean that we could have multiple different iterators like a DFS and a BFS iterator, etc.

But we could instead have it split between the iterator and the outside syntax:

for (item, index in {   // ... } 

This seems like what you see more often, but it seems to make implementation harder as the state is now split between the external environment and the iterator. Maybe not though.

The reason for asking is because there are these cases:

  • while loop
  • for loop
  • get item at index like string[10]
  • get item by name (hashtable)
  • etc.

It seems that if you want to have a generic API to iterating these things, or accessing these properties, you need an abstraction layer like the iterator on top of it. Wondering if that is true, or if not, what options there are.

Provide iterator while generating power set

I have written a code in C# to generate the power set of a given input list of integers.

public List<List<int>> GeneratePowerSet(List<int> Set) {     int setCount = Set.Count;     int powerSetCount = 1 << setCount;      // Temporary list to hold the all subsets     List<List<int>> subsets = new List<List<int>>();      // Outer loop running 2^n times     for (int i = 0; i < powerSetCount; i++)     {         // Inner loop running n times to check if j-th bit is set or not         for (int j = 0; j < setCount; j++)         {             // Temporary list to hold the current subset             List<int> subset = new List<int>();              // Check if j-th bit of i is 1 or no             if ((i & (1 << j)) != 0)             {                 subset.Add(Set[j]);             }             subsets.Add(subset);         }     }      return subsets; } 

As seen above I am making 2 temporary input lists which is causing extra overhead while generating the subsets.

Also for larger inputs I have observed it takes too long to compute the power sets.

How can I rewrite this method using the iterator pattern so that each time it yields out the current value without having me to make a temporary list.

Adding STL iterator support to custom collection class — followup

I read the excellent answer to the question Example of adding STL iterator support to custom collection class on this site; but would like furthermore the iterator class to be a nested class (because of shared types). The skeleton I want is:

template <typename T, std::size_t Capacity> class RingQueue {     ...     template <typename TT> class RingIter { ... operations ++, --, ... } public:     using iterator = RingIter<T>;     using const_iterator = RingIter<const T>;     using reverse_iterator = std::reverse_iterator<iterator>;     using const_reverse_iterator = std::reverse_iterator<const_iterator>;     ... define begin(), end(), ... };  // this is the line that doesn't compile! template<typename T, std::size_t Capacity, typename TT> class std::iterator_traits<RingQueue<T,Capacity>::RingIter<TT>>     {     public:         using difference_type = std::ptrdiff_t;         using size_type = std::size_t;         using value_type = TT;         using pointer = TT*;         using reference = TT&;         using iterator_category = std::random_access_iterator_tag;     }; 

and it’s in this last part that I’m stuck — whatever I tried, I can’t get to extend std::iterator_traits correctly.

Iterate over collection of Transactions via For Loop (Using Iterator)

The method below is basic insight of what I am planning to output: the account part works but when I try to print along with the transactions I get the nullpointer exception.

The reason is I am using my own queue implementation, underneath the method is my iterator so far but I have no clue what I am missing for this to not work?

         public void Display_Account() {          System.out.println("Student ID: " + Student_ID);          System.out.println("Student Name: " + Student_Name);          System.out.println("Student Email: " + Student_Email);          System.out.println("Creation Date (DD/MM/YYYY): " + Creation_Date);          System.out.println("Credit: " + Credit_Balance);          System.out.println("*----------------------*");           for (Student_Transaction Tr : Transaction) {               Tr.Display_Transaction();          }       }        // Queue uses class List.       import java.util.Iterator;        public class Queue <T> implements Iterable <T>       {        private List<T> queueList;        private int capacity;          // no-argument constructor        public Queue()        {           queueList = new List<>("queue");           capacity = 1;       } // end Queue no-argument constructor        @Override       public Iterator<T> iterator() {       return null;       }        class QueueIt implements Iterator<T> {         List<T> Starter = null;        // WHERE THE PROBLEM STARTS AT       @Override       public T next() {        if (Starter == null) {           Starter = queueList;       }         return null;       }        @Override       public boolean hasNext() {          if (Starter == null) {              return false;          }          else if (Starter != null) {             return false;          }              return true;          }      }      // Everything else in my code works except the above associated with       // iterator       // add object to queue      public void enqueue(T object)      {          queueList.insertAtBack(object);          capacity++;      } // end method enqueue       // remove object from queue      public T dequeue() throws EmptyListException      {           return queueList.removeFromFront();       } // end method dequeue       public void Decrement()       {          capacity--;      }       public int Size()       {         return capacity;       }       // determine if queue is empty      public boolean isEmpty()      {        return queueList.isEmpty();      } // end method isEmpty       // output queue contents      public void print()      {        queueList.print();      } // end method print     } 

Much appreciated if someone could point to what I am missing in my code because every example I’ve found are all relating to Linked List 🙁 though I know queue is basically a member of linked list and the bigger picture (java collections).