Search Results

Search found 908 results on 37 pages for 'iterator'.

Page 5/37 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Null pointer exception on .iterator() call

    - by Peter
    I'm getting a strange NullPointerException, evidently thrown by the following line of code: Iterator<Note> it = notes.iterator(); I've checked, and at the time the java.util.TreeSet notes is always non-null (with 15 elements). The TreeSet API says nothing about iterator() throwing NullPointerExceptions. What else could be going here?

    Read the article

  • returning of the iterator in C++

    - by helloWorld
    can somebody explain I can I return list iterator? list<Account>::iterator Company::findAccount(int id){ for(list<Account>::iterator i = listOfAccounts.begin(); i != listOfAccounts.end(); ++i){ if(i->getID() == id){ return i; } } return 0; } and also is it good practice, to return list iterator? edited also can use this function in the statesments: if(findAccount(id)){ throw "hey"; return; }

    Read the article

  • Using boost::iterator_adaptor

    - by Neil G
    I wrote a sparse vector class (see #1, #2.) I would like to provide two kinds of iterators: The first set, the regular iterators, can point any element, whether set or unset. If they are read from, they return either the set value or value_type(), if they are written to, they create the element and return the lvalue reference. Thus, they are: Random Access Traversal Iterator and Readable and Writable Iterator The second set, the sparse iterators, iterate over only the set elements. Since they don't need to lazily create elements that are written to, they are: Random Access Traversal Iterator and Readable and Writable and Lvalue Iterator I also need const versions of both, which are not writable. I can fill in the blanks, but not sure how to use boost::iterator_adaptor to start out. Here's what I have so far: class iterator : public boost::iterator_adaptor< iterator // Derived , value_type* // Base , boost::use_default // Value , boost::?????? // CategoryOrTraversal > class sparse_iterator : public boost::iterator_adaptor< iterator // Derived , value_type* // Base , boost::use_default // Value , boost::random_access_traversal_tag? // CategoryOrTraversal >

    Read the article

  • Call a block method on an iterator: each.magic.collect { ... }

    - by blinry
    I have a class with a custom each-method: class CurseArray < Array def each_safe each.do |element| unless element =~ "fuck" yield element end end end end And want to call block methods on those "selected" elements. For example: curse_array.each_safe.magic.collect {|element| "#{element} is a nice sentence."} I know there is a way to do this, but I've forgotten. Please help! :-)

    Read the article

  • Design pattern for adding / removing elements

    - by de3
    Wikipedia's definition for Iterator pattern design: the Iterator pattern is a design pattern in which iterators are used to access the elements of an aggregate object sequentially without exposing its underlying implementation. Iterator interface in java provides the following methods hasNext() next() remove() Is there a pattern design, or a java interface for inserting / deleting elements, and getting length of the aggregate object, in addition to iterating them? I know remove() is an optional method that can be used once per call to next(), but I am implementing a circular FIFO array and need a method delete() independent of iterator's next().

    Read the article

  • Is it possible to create a python iterator over pre-defined mutable data?

    - by Wilduck
    I might be doing this wrong, if I am, let me know, but I'm curious if the following is possible: I have a class that holds a number of dictionaries, each of which pairs names to a different set of objects of a given class. For example: items = {"ball" : ItemInstance1, "sword" : ItemInstance2} people = {"Jerry" : PersonInstance1, "Bob" : PersonInstance2, "Jill" : PersonInstance3} My class would then hold the current items and people that are availible, and these would be subject to change as the state changes: Class State: def __init__(self, items, people): self.items = items self.people = people I would like to define a iter() and next() method such that it iterates through all of the values in its attributes. My first question is whether or not this is possible. If it is, will it be able to support a situation as follows: I define items and people as above then: state = State(items, people) for names, thing in state: print name + " is " + thing.color items[cheese] = ItemInstance3 for names, thing in state: print name + " weighs " + thing.weight While I feel like this would be usefull in the code I have, I don't know if it's either possible or the right approach. Everything I've read about user defined iterators has suggested that each instance of them is one use only.

    Read the article

  • Python file iterator over a binary file with newer idiom.

    - by drewk
    In Python, for a binary file, I can write this: buf_size=1024*64 # this is an important size... with open(file, "rb") as f: while True: data=f.read(buf_size) if not data: break # deal with the data.... With a text file that I want to read line-by-line, I can write this: with open(file, "r") as file: for line in file: # deal with each line.... Which is shorthand for: with open(file, "r") as file: for line in iter(file.readline, ""): # deal with each line.... This idiom is documented in PEP 234 but I have failed to locate a similar idiom for binary files. I have tried this: >>> with open('dups.txt','rb') as f: ... for chunk in iter(f.read,''): ... i+=1 >>> i 1 # 30 MB file, i==1 means read in one go... I tried putting iter(f.read(buf_size),'') but that is a syntax error because of the parens after the callable in iter(). I know I could write a function, but is there way with the default idiom of for chunk in file: where I can use a buffer size versus a line oriented? Thanks for putting up with the Python newbie trying to write his first non-trivial and idiomatic Python script.

    Read the article

  • How does Ruby's Enumerator object iterate externally over an internal iterator?

    - by Salman Paracha
    As per Ruby's documentation, the Enumerator object uses the each method (to enumerate) if no target method is provided to the to_enum or enum_for methods. Now, let's take the following monkey patch and its enumerator, as an example o = Object.new def o.each yield 1 yield 2 yield 3 end e = o.to_enum loop do puts e.next end Given that the Enumerator object uses the each method to answer when next is called, how do calls to the each method look like, every time next is called? Does the Enumeartor class pre-load all the contents of o.each and creates a local copy for enumeration? Or is there some sort of Ruby magic that hangs the operations at each yield statement until next is called on the enumeartor? If an internal copy is made, is it a deep copy? What about I/O objects that could be used for external enumeration? I'm using Ruby 1.9.2.

    Read the article

  • What to return as an iterator when there is no container?

    - by DaClown
    I have an inheritance structure of objects with begin() and end() as pure virtual member functions in the base class. From this objects I'm planning to build a composite structure. This inner objects have std::vector member the begin() and end() get their data from. But in a leaf class there is no vector. Now I try to find a return value for begin() and end() in the leaf classes. What would be a good way to do that? The easiest way would be to have a vector member in the leaf classes with no elements in it to fuel begin() and end(), but this just doesn't feel right.

    Read the article

  • How can I make an iterator that never ends?

    - by Soldier.moth
    I was just wondering what the easiest way to iterate over a set indefinitely, i.e. when it reaches the end it next(); calls the first object. I'm assuming that this is not an already predefined function in Java, so just looking for the easiest way to implement this in Java.

    Read the article

  • How can I have a Foo* iterator to a vector of Foo?

    - by mghie
    If I have a class that contains a std::list<Foo>, how can I implement iterators to a Foo* collection, preferably without using boost? I'd rather not maintain a parallel collection of pointers. For now I have std::list<Foo>, mostly so that removing or inserting an element does not invalidate all other iterators, but would it be possible to implement other iterators too, so that the collection type used in the implementation is opaque to the user of the class?

    Read the article

  • C++ Template Iterator error

    - by gprime
    I am going over some code i wrote in 2006 as an undergrad. It's a simple genetic algorithm library written in C++ using templates. It use to work in 2006 when i coded it with visual studio, but now when i am trying to run it in xcode i get compile errors. This function is giving me errors: friend bool operator==(const TSPGenome<T> & t1, const TSPGenome<T> & t2) { // loop through each interator and check to see if the two genomes have the same values if(t1.genome_vec->size() != t2.genome_vec->size()) return false; else { // iterate through each vector<T>::iterator it_t1; vector<T>::iterator it_t2; it_t1 = t1.genome_vec->begin(); for(it_t2 = t2.genome_vec->begin(); it_t2 != t2.genome_vec->end(); ++it_t2, ++it_t1) { if(*it_t2 != *it_t1) return false; } } // everything seems good return true; } xcode complains about these two lines not having ; before it_t1 and it_t2. vector<T>::iterator it_t1; vector<T>::iterator it_t2; Is it because the vector type it T? I declared it in the class as follows: template <typename T> class TSPGenome : public Genome { Any help would be appreciated. Thanks!

    Read the article

  • PHP, when to use iterators, how to buffer results?

    - by Jon L.
    When is it best to use Iterators in PHP, and how can they be implemented to best avoid loading all objects into memory simultaneously? Do any constructs exist in PHP so that we can queue up results of an operation for use with an Iterator, while again avoiding loading all objects into memory simultaneously? An example would be a curl HTTP request against a REST server In the case of an HTTP request that returns all results at once (a la curl), would we be better off to go with streaming results, and if so, are there any limitations or pitfalls to be aware of? If using streaming, is it better to replace curl with a PHP native stream/socket? My intention is to implement Iterators for a REST client, and separately a document ORM that I'm maintaining, but only if I can do so while gaining benefits from reduced memory usage, increased performance, etc. Thanks in advance for any responses :-)

    Read the article

  • Java->Scala Remove Iterator<T>-Element from a JavaConversions-wrapped Iterable

    - by ifischer
    I have to translate the following code from Java to Scala: for (Iterator<ExceptionQueuedEvent> i = getUnhandledExceptionQueuedEvents().iterator(); i.hasNext();) { ExceptionQueuedEvent event = i.next(); try { //do something } finally { i.remove(); } } I'm using the JavaConversions library to wrap the Iterable. But as i'm not using the original Iterator, i don't know how to remove the current element correctly from the collection the same way as i did in Java: import scala.collection.JavaConversions._ (...) for (val event <- events) { try { //do something } finally { //how can i remove the current event from events? } } Can someone help me? I guess it's easy, but i'm still kinda new to Scala and don't understand what's going on when Scala wraps something of Java.

    Read the article

  • StreamTokenizer Iterator Adapter help

    - by alpdog14
    I have this StreamTokenizer Iterator Adapter that is suppose to create a Tokenizer Iterator Index Builder then build the index from a STIA wrapped around a StreamTokenizer. I am having trouble implementing the hasNext and Next for my STIA, can anyone help me, here is my class: public class StreamTokenizerIteratorAdapter implements Iterator<Token> { DefaultIndexImpl index; StreamTokenizer source; public StreamTokenizerIteratorAdapter(final StreamTokenizer source) { if (source == null) throw new IllegalArgumentException("source == null"); } @Override public boolean hasNext() { return !index.isEmpty(); } public Token next() { if(!index.isEmpty()) return next(); else return null; } @Override public void remove() { throw new UnsupportedOperationException(); } } Should I be using the source element in the hasNext() and next()?

    Read the article

  • Internal class and access to external members.

    - by Knowing me knowing you
    I have question with this same title here but now as I'll present in code below this seems to behave in the opposite way to the way explained to me in my first question with the same title. Ok code: class LINT_rep { private: char* my_data_; //stores separately every single digit from a number public: class Iterator:public iterator<bidirectional_operator_tag,char*> { Iterator(const LINT_rep&); }; }; #include "StdAfx.h" #include "LINT_rep.h" LINT_rep::Iterator::Iterator(const LINT_rep& owner):myData_(nullptr) { myData_ = owner.my_data_; /* HERE I'M ACCESSING my_data WHICH IS PRIVATE AND THIS CODE COMPILES ON VS2010 ULTIMATE BUT IT SHOULDN'T BECAUSE my_data IS PRIVATE AND OTHER CLASS SHOULDN'T HAVE ACCESS TO IT'S PRIVATE MEMB. AS EXPLAINED TO ME IN QUESTION TO WHICH I;VE PROVIDED LINK. */ } Question in the code. Thanks.

    Read the article

  • enumerate all combinations in c++

    - by BCS
    My question is similar to this combinations question but in my case I have N (N 4) small sets (1-2 items per set for now might go to 3 maybe 4) and want to generate each combination of one item from each set. The current solution looks somethinging along the lines of this for(T:: iterator a = setA.begin(); a != setA.end(); ++a) for(T:: iterator b = setB.begin(); b != setB.end(); ++b) for(T:: iterator c = setC.begin(); c != setC.end(); ++c) for(T:: iterator d = setD.begin(); d != setD.end(); ++d) for(T:: iterator e = setE.begin(); e != setE.end(); ++e) something(*a,*b,*c,*d,*e); Simple, effective, probably reasonably efficient, but ugly and not very extensible. Does anyone know of a better/cleaner way to do this?

    Read the article

  • More advanced usage of interfaces

    - by owca
    To be honest I'm not quite sure if I understand the task myself :) I was told to create class MySimpleIt, that implements Iterator and Iterable and will allow to run the provided test code. Arguments and variables of objects cannot be either Collections or arrays. The code : MySimpleIt msi=new MySimple(10,100, MySimpleIt.PRIME_NUMBERS); for(int el: msi) System.out.print(el+" "); System.out.println(); msi.setType(MySimpleIterator.ODD_NUMBERS); msi.setLimits(15,30); for(int el: msi) System.out.print(el+" "); System.out.println(); msi.setType(MySimpleIterator.EVEN_NUMBERS); for(int el: msi) System.out.print(el+" "); System.out.println(); The result I should obtain : 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 15 17 19 21 23 25 27 29 16 18 20 22 24 26 28 30 And here's my code : import java.util.Iterator; interface MySimpleIterator{ static int ODD_NUMBERS=0; static int EVEN_NUMBERS = 1; static int PRIME_NUMBERS = 2; int setType(int i); } public class MySimpleIt implements Iterable, Iterator, MySimpleIterator { public MySimple my; public MySimpleIt(MySimple m){ my = m; } public int setType(int i){ my.numbers = i; return my.numbers; } public void setLimits(int d, int u){ my.down = d; my.up = u; } public Iterator iterator(){ Iterator it = this.iterator(); return it; } public void remove(){ } public Object next(){ Object o = new Object(); return o; } public boolean hasNext(){ return true; } } class MySimple { public int down; public int up; public int numbers; public MySimple(int d, int u, int n){ down = d; up = u; numbers = n; } } In the test code I have error in line when creating MySimpleIt msi object, as it finds MySimple instead of MySimpleIt. Also I have errors in for-each loops, because compiler wants 'ints' there instead of Object. Anyone has any idea on how to solve it ?

    Read the article

  • When to write an iterator?

    - by Jon
    I know this is probably a silly question.. When would I need to write my own iterator? Is it just when designing my own container class? Are there any other times when I would want to create my own iterator? Examples would be appropriated. -Jon

    Read the article

  • Correct way of setting a custom FileInfo class to an Iterator

    - by Gordon
    I am trying to set a custom class to an Iterator through the setInfoClass method: Use this method to set a custom class which will be used when getFileInfo and getPathInfo are called. The class name passed to this method must be derived from SplFileInfo. My class is like this (simplified example): class MyFileInfo extends SplFileInfo { public $props = array( 'foo' => '1', 'bar' => '2' ); } The iterator code is this: $rit = new RecursiveIteratorIterator( new RecursiveDirectoryIterator('/some/file/path/'), RecursiveIteratorIterator::SELF_FIRST); Since RecursiveDirectoryIterator is by inheritance through DirectoryIterator also an SplFileInfo object, it provides the setInfoClass method (it's not listed in the manual, but reflection shows it's there). Thus I can do: $rit->getInnerIterator()->setInfoClass('MyFileInfo'); All good up to here, but when iterating over the directory with foreach($rit as $file) { var_dump( $file ); } I get the following weird result object(MyFileInfo)#4 (3) { ["props"]=>UNKNOWN:0 ["pathName":"SplFileInfo":private]=>string(49) "/some/file/path/someFile.txt" ["fileName":"SplFileInfo":private]=>string(25) "someFile.txt" } So while MyFileInfo is picked up, I cannot access it's properties. If I add custom methods, I can invoke them fine, but any properties are UNKNOWN. If I don't set the info class to the iterator, but to the SplFileInfo object (like shown in the example in the manual), it will give the same UNKNOWN result: foreach($rit as $file) { // $file is a SplFileInfo instance $file->setInfoClass('MyFileInfo'); var_dump( $file->getFileInfo() ); } However, it will work when I do foreach($rit as $file) { $file = new MyFileInfo($file); var_dump( $file ); } Unfortunately, the code I a want to use this in is somewhat more complicated and stacks some more iterators. Creating the MyFileInfo class like this is not an option. So, does anyone know how to get this working or why PHP behaves this weird? Thanks.

    Read the article

  • How to access valuestack objects within struts iterator?

    - by Monika Michael
    I have following code - <s:iterator value="reviews"> <img src="<s:property value="#request.restaurant.portalImage.url" />" /> <s:property value="user.firstName" /> <s:property value="user.lastName" /> <s:property value="rating" /> <s:property value="review" /> </s:iterator> reviews is a list of review objects which contain details of a review, such as rating and name of user. My problem is that i'm not able to access any of the objects present on the valuestack within the loop. Outside the loop <s:property value="#request.restaurant.portalImage.url" /> works correctly. But within the loop it prints null. AFAIK an iterator pushes it's collection on the valuestack so that all ognl expressions resolve against it. But I've used # which means I'm explicitly specifying the root object for resolution. Why is it still not working?

    Read the article

  • Java - When to use Iterators?

    - by Walter White
    Hi all, I am trying to better understand when I should and should not use Iterators. To me, whenever I have a potentially large amount of data to iterate through, I write an Iterator for it. If it also lends itself to the Iterator interface, then it seems like a win. I was reading a little bit that there is a lot of overhead with using an Iterator. A good example of where I used an Iterator was to iterate through a bunch of SQL scripts to execute one query at a time, reading it in, then executing it. Is there another performance trade off I should be aware of? Before I used iterators, I would read the entire String of SQL commands to execute into an ArrayList, and the iterate through that. If the import is rather large (like for geolocation data, then the server tends to get bogged down). Walter

    Read the article

  • How to iterate over modifed std::map values?

    - by Frank
    I have an std::map, and I would like to define an iterator that returns modified values. Typically, a std::map<int,double>::iterator iterates over std::pair<int,double>, and I would like the same behavior, just the double value is multiplied by a constant. I tried it with boost::transform_iterator, but it doesn't compile: #include <map> #include <boost/iterator/transform_iterator.hpp> #include <boost/functional.hpp> typedef std::map<int,double> Map; Map m; m[100] = 2.24; typedef boost::binder2nd< std::multiplies<double> > Function; typedef boost::transform_iterator<Function, Map::value_type*> MultiplyIter; MultiplyIter begin = boost::make_transform_iterator(m.begin(), Function(std::multiplies<double>(), 4)); // now want to similarly create an end iterator // and then iterate over the modified map The error is: error: conversion from 'boost ::transform_iterator< boost::binder2nd<multiplies<double> >, gen_map<int, double>::iterator , boost::use_default, boost::use_default >' to non-scalar type 'boost::transform_iterator< boost::binder2nd<multiplies<double> >, pair<const int, double> * , boost::use_default, boost::use_default >' requested What is gen_map and do I really need it? I adapted the transform_iterator tutorial code from here to write this code ...

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >