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(System.in);       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(" " +it.next() +" "); 

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

Linked_List.h

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;     }; }; 

Linked_List.cpp

#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:

asdfasdfasd...256fasdfasdfasdf 

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 iterator.next()) {   // ... } 

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).

iterator class using generator function

It is sometimes necessary for a generator function to expose state. In those situations it is advised to wrap the generator function as method __iter__ in a class. Here is an example:

class C:     def __init__(self):         self.next = self.__iter__().__next__     def __iter__(self):         for i in range(4):             yield i                         self.state = i 

It is convenient to use this in a for loop since the for loop will call iter() on the object, however, the object itself is not an iterator, so you cannot do this:

c = C() print(next(c)) 

Which is inconvenient. To get around this inconvenience I have come up with the following class:

class C:     def __init__(self):         self.next = self.__iter__().__next__     def __iter__(self):         for i in range(4):             yield i                         self.state = i     def __next__(self):         return self.next() 

Usage example:

c = C() while 1:     try:         num = next(c)         print(num)         if num == 2:             print("state:", c.state)     except Exception:         break 

Is this the best way to design the class? I haven’t seen this technique used anywhere else so I’m wondering why everyone else isn’t using it, since the C objects can be used both as iterators and as iterables.

An index-based C++ iterator

I’ve got a case where I need to use sequential containers but need to avoid iterator invalidation on reallocations. I’ve got the idea to make an iterator from a tuple of (Container, Index), so for a slight memory-overhead the iterators stay valid (out of range error is possible on removal). This is my implementation (trying to satisfy LegacyRandomAccessIterator):

template <typename Collection> struct index_based_iterator { private:     using collection_value_type = typename Collection::value_type;  public:     /**      * std::iterator_traits      */     using difference_type = std::ptrdiff_t;     using value_type = std::conditional_t<         std::is_const_v<Collection>,         const collection_value_type,         collection_value_type     >;     using pointer = value_type*;     using reference = value_type&;     using iterator_category = std::random_access_iterator_tag;      explicit index_based_iterator(Collection& coll, std::uintptr_t idx)         : m_Collection(&coll), m_Index(idx) {     }      index_based_iterator(index_based_iterator const&) = default;     index_based_iterator(index_based_iterator&&) = default;      index_based_iterator& operator=(index_based_iterator const&) = default;     index_based_iterator& operator=(index_based_iterator&&) = default;      /**      * Satisfy Swappable.      */     void swap(index_based_iterator& o) {         std::swap(m_Collection, o.m_Collection);         std::swap(m_Index, o.m_Index);     }      friend void swap(index_based_iterator& i1, index_based_iterator& i2) {         i1.swap(i2);     }      /**      * LegacyIterator operations.      */     reference operator*() {         return (*m_Collection)[m_Index];     }      index_based_iterator& operator++() {         ++m_Index;         return *this;     }      /**      * Satisfy EqualityComparable.      */     friend bool     operator==(index_based_iterator const& i1, index_based_iterator const& i2) {         return (i1.m_Collection == i2.m_Collection)             && (i1.m_Index == i2.m_Index);     }      /**      * LegacyInputIterator (and LegacyForwardIterator) operations.      */     friend bool     operator!=(index_based_iterator const& i1, index_based_iterator const& i2) {         return !(i1 == i2);     }      pointer operator->() {         return &(operator*());     }      index_based_iterator operator++(int) {         auto other = *this;         operator++();         return other;     }      /**      * LegacyBidirectionalIterator operations.      */     index_based_iterator& operator--() {         --m_Index;         return *this;     }      index_based_iterator operator--(int) {         auto other = *this;         operator--();         return other;     }      /**      * LegacyRangomAccessIterator operations.      */     index_based_iterator& operator+=(difference_type n) {         m_Index += n;         return *this;     }      friend index_based_iterator     operator+(index_based_iterator i, difference_type n) {         i += n;         return i;     }      friend index_based_iterator     operator+(difference_type n, index_based_iterator const& i) {         return i + n;     }      index_based_iterator& operator-=(difference_type n) {         m_Index -= n;         return *this;     }      friend index_based_iterator     operator-(index_based_iterator i, difference_type n) {         i -= n;         return i;     }      friend difference_type     operator-(index_based_iterator const& i1, index_based_iterator const& i2) {         return difference_type(i1.m_Index) - difference_type(i2.m_Index);     }      reference operator[](difference_type n) {         return *(*this + n);     }      friend bool     operator<(index_based_iterator const& a, index_based_iterator const& b) {         return (b - a) > 0;     }      friend bool     operator>(index_based_iterator const& a, index_based_iterator const& b) {         return b < a;     }      friend bool     operator>=(index_based_iterator const& a, index_based_iterator const& b) {         return !(a < b);     }      friend bool     operator<=(index_based_iterator const& a, index_based_iterator const& b) {         return !(a > b);     }  private:     Collection* m_Collection;     std::uintptr_t m_Index; }; 

Is this actually correct in terms of C++17 random access iterators? Could the code be improved (mainly code-size reduction)?