Search Results

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

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

  • java util iterator but cannot import java.util.iterator

    - by qwertzuiop13
    Given this Code import java.util.Iterator; private static List<String> someList = new ArrayList<String>(); public static void main(String[] args) { someList.add("monkey"); someList.add("donkey"); //Code works when I change Iterator to java.util.Iterator, but import //is not possible? for(Iterator<String> i = someList.iterator(); i.hasNext(); ) { String item = i.next(); System.out.println(item); } } I receive the error: The type Iterator is not generic; it cannot be parameterized with arguments Eclipse tells me that the import java.util.iterator conflicts with a type defined in the same file. lol... ?

    Read the article

  • Is it bad practice to make an iterator that is aware of its own end

    - by aaronman
    For some background of why I am asking this question here is an example. In python the method chain chains an arbitrary number of ranges together and makes them into one without making copies. Here is a link in case you don't understand it. I decided I would implement chain in c++ using variadic templates. As far as I can tell the only way to make an iterator for chain that will successfully go to the next container is for each iterator to to know about the end of the container (I thought of a sort of hack in where when != is called against the end it will know to go to the next container, but the first way seemed easier and safer and more versatile). My question is if there is anything inherently wrong with an iterator knowing about its own end, my code is in c++ but this can be language agnostic since many languages have iterators. #ifndef CHAIN_HPP #define CHAIN_HPP #include "iterator_range.hpp" namespace iter { template <typename ... Containers> struct chain_iter; template <typename Container> struct chain_iter<Container> { private: using Iterator = decltype(((Container*)nullptr)->begin()); Iterator begin; const Iterator end;//never really used but kept it for consistency public: chain_iter(Container & container, bool is_end=false) : begin(container.begin()),end(container.end()) { if(is_end) begin = container.end(); } chain_iter & operator++() { ++begin; return *this; } auto operator*()->decltype(*begin) { return *begin; } bool operator!=(const chain_iter & rhs) const{ return this->begin != rhs.begin; } }; template <typename Container, typename ... Containers> struct chain_iter<Container,Containers...> { private: using Iterator = decltype(((Container*)nullptr)->begin()); Iterator begin; const Iterator end; bool end_reached = false; chain_iter<Containers...> next_iter; public: chain_iter(Container & container, Containers& ... rest, bool is_end=false) : begin(container.begin()), end(container.end()), next_iter(rest...,is_end) { if(is_end) begin = container.end(); } chain_iter & operator++() { if (begin == end) { ++next_iter; } else { ++begin; } return *this; } auto operator*()->decltype(*begin) { if (begin == end) { return *next_iter; } else { return *begin; } } bool operator !=(const chain_iter & rhs) const { if (begin == end) { return this->next_iter != rhs.next_iter; } else return this->begin != rhs.begin; } }; template <typename ... Containers> iterator_range<chain_iter<Containers...>> chain(Containers& ... containers) { auto begin = chain_iter<Containers...>(containers...); auto end = chain_iter<Containers...>(containers...,true); return iterator_range<chain_iter<Containers...>>(begin,end); } } #endif //CHAIN_HPP

    Read the article

  • What do you think of this iterator syntax?

    - by ChaosPandion
    I've been working on an ECMAScript dialect for quite some time now and have reached a point where I am comfortable adding new language features. I would love to hear some thoughts and suggestions on the syntax. Example iterator Numbers { yield 1; yield 2; yield 3; if (true) { yield break; } yield continue iterator { yield 4; yield 5; yield 6; }; } Syntax IteratorDeclaration:     iterator  Identifier  {  IteratorBody  } IteratorExpression:     iterator  Identifieropt  {  IteratorBody  } IteratorBody:     IteratorStatementsopt IteratorStatements:     IteratorStatement IteratorStatementsopt IteratorStatement:     Statement but not one of BreakStatement ContinueStatement ReturnStatement     YieldStatement     YieldBreakStatement     YieldContinueStatement YieldStatement:     yield  Expression  ; YieldBreakStatement:     yield  break  ; YieldContinueStatement:     yield  continue  Expression  ;

    Read the article

  • Overloading *(iterator + n) and *(n + iterator) in a C++ iterator class?

    - by exscape
    (Note: I'm writing this project for learning only; comments about it being redundant are... uh, redundant. ;) I'm trying to implement a random access iterator, but I've found very little literature on the subject, so I'm going by trial and error combined with Wikpedias list of operator overload prototypes. It's worked well enough so far, but I've hit a snag. Code such as exscape::string::iterator i = string_instance.begin(); std::cout << *i << std::endl; works, and prints the first character of the string. However, *(i + 1) doesn't work, and neither does *(1 + i). My full implementation would obviously be a bit too much, but here's the gist of it: namespace exscape { class string { friend class iterator; ... public: class iterator : public std::iterator<std::random_access_iterator_tag, char> { ... char &operator*(void) { return *p; // After some bounds checking } char *operator->(void) { return p; } char &operator[](const int offset) { return *(p + offset); // After some bounds checking } iterator &operator+=(const int offset) { p += offset; return *this; } const iterator operator+(const int offset) { iterator out (*this); out += offset; return out; } }; }; } int main() { exscape::string s = "ABCDEF"; exscape::string::iterator i = s.begin(); std::cout << *(i + 2) << std::endl; } The above fails with (line 632 is, of course, the *(i + 2) line): string.cpp: In function ‘int main()’: string.cpp:632: error: no match for ‘operator*’ in ‘*exscape::string::iterator::operator+(int)(2)’ string.cpp:105: note: candidates are: char& exscape::string::iterator::operator*() *(2 + i) fails with: string.cpp: In function ‘int main()’: string.cpp:632: error: no match for ‘operator+’ in ‘2 + i’ string.cpp:434: note: candidates are: exscape::string exscape::operator+(const char*, const exscape::string&) My guess is that I need to do some more overloading, but I'm not sure what operator I'm missing.

    Read the article

  • nested iterator errors

    - by Sean
    //arrayList.h #include<iostream> #include<sstream> #include<string> #include<algorithm> #include<iterator> using namespace std; template<class T> class arrayList{ public: // constructor, copy constructor and destructor arrayList(int initialCapacity = 10); arrayList(const arrayList<T>&); ~arrayList() { delete[] element; } // ADT methods bool empty() const { return listSize == 0; } int size() const { return listSize; } T& get(int theIndex) const; int indexOf(const T& theElement) const; void erase(int theIndex); void insert(int theIndex, const T& theElement); void output(ostream& out) const; // additional method int capacity() const { return arrayLength; } void reverse(); // new defined // iterators to start and end of list class iterator; class seamlessPointer; seamlessPointer begin() { return seamlessPointer(element); } seamlessPointer end() { return seamlessPointer(element + listSize); } // iterator for arrayList class iterator { public: // typedefs required by C++ for a bidirectional iterator typedef bidirectional_iterator_tag iterator_category; typedef T value_type; typedef ptrdiff_t difference_type; typedef T* pointer; typedef T& reference; // constructor iterator(T* thePosition = 0) { position = thePosition; } // dereferencing operators T& operator*() const { return *position; } T* operator->() const { return position; } // increment iterator& operator++() // preincrement { ++position; return *this; } iterator operator++(int) // postincrement { iterator old = *this; ++position; return old; } // decrement iterator& operator--() // predecrement { --position; return *this; } iterator operator--(int) // postdecrement { iterator old = *this; --position; return old; } // equality testing bool operator!=(const iterator right) const { return position != right.position; } bool operator==(const iterator right) const { return position == right.position; } protected: T* position; }; // end of iterator class class seamlessPointer: public arrayList<T>::iterator { // constructor seamlessPointer(T *thePosition) { iterator::position = thePosition; } //arithmetic operators seamlessPointer & operator+(int n) { arrayList<T>::iterator::position += n; return *this; } seamlessPointer & operator+=(int n) { arrayList<T>::iterator::position += n; return *this; } seamlessPointer & operator-(int n) { arrayList<T>::iterator::position -= n; return *this; } seamlessPointer & operator-=(int n) { arrayList<T>::iterator::position -= n; return *this; } T& operator[](int n) { return arrayList<T>::iterator::position[n]; } bool operator<(seamlessPointer &rhs) { if(int(arrayList<T>::iterator::position - rhs.position) < 0) return true; return false; } bool operator<=(seamlessPointer & rhs) { if (int(arrayList<T>::iterator::position - rhs.position) <= 0) return true; return false; } bool operator >(seamlessPointer & rhs) { if (int(arrayList<T>::iterator::position - rhs.position) > 0) return true; return false; } bool operator >=(seamlessPointer &rhs) { if (int(arrayList<T>::iterator::position - rhs.position) >= 0) return true; return false; } }; protected: // additional members of arrayList void checkIndex(int theIndex) const; // throw illegalIndex if theIndex invalid T* element; // 1D array to hold list elements int arrayLength; // capacity of the 1D array int listSize; // number of elements in list }; #endif //main.cpp #include<iostream> #include"arrayList.h" #include<fstream> #include<algorithm> #include<string> using namespace std; bool compare_nocase (string first, string second) { unsigned int i=0; while ( (i<first.length()) && (i<second.length()) ) { if (tolower(first[i])<tolower(second[i])) return true; else if (tolower(first[i])>tolower(second[i])) return false; ++i; } if (first.length()<second.length()) return true; else return false; } int main() { ifstream fin; ofstream fout; string str; arrayList<string> dict; fin.open("dictionary"); if (!fin.good()) { cout << "Unable to open file" << endl; return 1; } int k=0; while(getline(fin,str)) { dict.insert(k,str); // cout<<dict.get(k)<<endl; k++; } //sort the array sort(dict.begin, dict.end(),compare_nocase); fout.open("sortedDictionary"); if (!fout.good()) { cout << "Cannot create file" << endl; return 1; } dict.output(fout); fin.close(); return 0; } Two errors are: ..\src\test.cpp: In function 'int main()': ..\src\test.cpp:50:44: error: no matching function for call to 'sort(<unresolved overloaded function type>, arrayList<std::basic_string<char> >::seamlessPointer, bool (&)(std::string, std::string))' ..\src\/arrayList.h: In member function 'arrayList<T>::seamlessPointer arrayList<T>::end() [with T = std::basic_string<char>]': ..\src\test.cpp:50:28: instantiated from here ..\src\/arrayList.h:114:3: error: 'arrayList<T>::seamlessPointer::seamlessPointer(T*) [with T = std::basic_string<char>]' is private ..\src\/arrayList.h:49:44: error: within this context Why do I get these errors? Update I add public: in the seamlessPointer class and change begin to begin() Then I got the following errors: ..\hw3prob2.cpp:50:46: instantiated from here c:\wascana\mingw\bin\../lib/gcc/mingw32/4.5.0/include/c++/bits/stl_algo.h:5250:4: error: no match for 'operator-' in '__last - __first' ..\/arrayList.h:129:21: note: candidate is: arrayList<T>::seamlessPointer& arrayList<T>::seamlessPointer::operator-(int) [with T = std::basic_string<char>, arrayList<T>::seamlessPointer = arrayList<std::basic_string<char> >::seamlessPointer] c:\wascana\mingw\bin\../lib/gcc/mingw32/4.5.0/include/c++/bits/stl_algo.h:5252:4: instantiated from 'void std::sort(_RAIter, _RAIter, _Compare) [with _RAIter = arrayList<std::basic_string<char> >::seamlessPointer, _Compare = bool (*)(std::basic_string<char>, std::basic_string<char>)]' ..\hw3prob2.cpp:50:46: instantiated from here c:\wascana\mingw\bin\../lib/gcc/mingw32/4.5.0/include/c++/bits/stl_algo.h:2190:7: error: no match for 'operator-' in '__last - __first' ..\/arrayList.h:129:21: note: candidate is: arrayList<T>::seamlessPointer& arrayList<T>::seamlessPointer::operator-(int) [with T = std::basic_string<char>, arrayList<T>::seamlessPointer = arrayList<std::basic_string<char> >::seamlessPointer] Then I add operator -() in the seamlessPointer class ptrdiff_t operator -(seamlessPointer &rhs) { return (arrayList<T>::iterator::position - rhs.position); } Then I compile successfully. But when I run it, I found memeory can not read error. I debug and step into and found the error happens in stl function template<typename _RandomAccessIterator, typename _Distance, typename _Tp, typename _Compare> void __adjust_heap(_RandomAccessIterator __first, _Distance __holeIndex, _Distance __len, _Tp __value, _Compare __comp) { const _Distance __topIndex = __holeIndex; _Distance __secondChild = __holeIndex; while (__secondChild < (__len - 1) / 2) { __secondChild = 2 * (__secondChild + 1); if (__comp(*(__first + __secondChild), *(__first + (__secondChild - 1)))) __secondChild--; *(__first + __holeIndex) = _GLIBCXX_MOVE(*(__first + __secondChild)); ////// stop here __holeIndex = __secondChild; } Of course, there must be something wrong with the customized operators of iterator. Does anyone know the possible reason? Thank you.

    Read the article

  • can't increment Glib::ustring::iterator (getting "invalid lvalue in increment" compiler error)

    - by davka
    in the following code: int utf8len(char* s, int len) { Glib::ustring::iterator p( string::iterator(s) ); Glib::ustring::iterator e ( string::iterator(s+len) ); int i=0; for (; p != e; p++) // ERROR HERE! i++; return i; } I get the compiler error on the for line, which is sometimes "invalid lvalue in increment", and sometimes "ISO C++ forbids incrementing a pointer of type etc... ". Yet, the follwing code: int utf8len(char* s) { Glib::ustring us(s); int i=0; for (Glib::ustring::iterator p = us.begin(); p != us.end(); p++) i++; return i; } compiles and works fine. according the Glib::ustring documentation and the include file, ustring iterator can be constructed from std::string iterator, and has operator++() defined. Weird? BONUS QUESTION :) Is there a difference in C++ between the 2 ways of defining a variable: classname ob1( initval ); classname ob1 = initval; I believed that they are synonymous; yet, if I change Glib::ustring::iterator p( string::iterator(s) ); to Glib::ustring::iterator p = string::iterator(s); I get a compiler error (gcc 4.1.2) conversion from ‘__gnu_cxx::__normal_iterator, std::allocator ’ to non-scalar type ‘Glib::ustring_Iterator<__gnu_cxx::__normal_iterator, std::allocator ’ requesed thanks a lot!

    Read the article

  • C++ iterator and const_iterator problem for own container class

    - by BaCh
    Hi there, I'm writing an own container class and have run into a problem I can't get my head around. Here's the bare-bone sample that shows the problem. It consists of a container class and two test classes: one test class using a std:vector which compiles nicely and the second test class which tries to use my own container class in exact the same way but fails miserably to compile. #include <vector> #include <algorithm> #include <iterator> using namespace std; template <typename T> class MyContainer { public: class iterator { public: typedef iterator self_type; inline iterator() { } }; class const_iterator { public: typedef const_iterator self_type; inline const_iterator() { } }; iterator begin() { return iterator(); } const_iterator begin() const { return const_iterator(); } }; // This one compiles ok, using std::vector class TestClassVector { public: void test() { vector<int>::const_iterator I=myc.begin(); } private: vector<int> myc; }; // this one fails to compile. Why? class TestClassMyContainer { public: void test(){ MyContainer<int>::const_iterator I=myc.begin(); } private: MyContainer<int> myc; }; int main(int argc, char ** argv) { return 0; } gcc tells me: test2.C: In member function ‘void TestClassMyContainer::test()’: test2.C:51: error: conversion from ‘MyContainer::iterator’ to non-scalar type ‘MyContainer::const_iterator’ requested I'm not sure where and why the compiler wants to convert an iterator to a const_iterator for my own class but not for the STL vector class. What am I doing wrong?

    Read the article

  • Is an "infinite" iterator bad design?

    - by Adamski
    Is it generally considered bad practice to provide Iterator implementations that are "infinite"; i.e. where calls to hasNext() always(*) return true? Typically I'd say "yes" because the calling code could behave erratically, but in the below implementation hasNext() will return true unless the caller removes all elements from the List that the iterator was initialised with; i.e. there is a termination condition. Do you think this is a legitimate use of Iterator? It doesn't seem to violate the contract although I suppose one could argue it's unintuitive. public class CyclicIterator<T> implements Iterator<T> { private final List<T> l; private Iterator it; public CyclicIterator<T>(List<T> l) { this.l = l; this.it = l.iterator(); } public boolean hasNext() { return !l.isEmpty(); } public T next() { T ret; if (!hasNext()) { throw new NoSuchElementException(); } else if (it.hasNext()) { ret = it.next(); } else { it = l.iterator(); ret = it.next(); } return ret; } public void remove() { it.remove(); } }

    Read the article

  • Using boost::iterator

    - 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: template<typename T> class sparse_vector { public: typedef size_t size_type; typedef T value_type; private: typedef T& true_reference; typedef const T* const_pointer; typedef sparse_vector<T> self_type; struct ElementType { ElementType(size_type i, T const& t): index(i), value(t) {} ElementType(size_type i, T&& t): index(i), value(t) {} ElementType(size_type i): index(i) {} ElementType(ElementType const&) = default; size_type index; value_type value; }; typedef vector<ElementType> array_type; public: typedef T* pointer; typedef T& reference; typedef const T& const_reference; private: size_type size_; mutable typename array_type::size_type sorted_filled_; mutable array_type data_; // lots of code for various algorithms... public: class sparse_iterator : public boost::iterator_adaptor< sparse_iterator // Derived , array_type::iterator // Base (the internal array) (this paramater does not compile! -- says expected a type, got 'std::vector::iterator'???) , boost::use_default // Value , boost::random_access_traversal_tag? // CategoryOrTraversal > class iterator_proxy { ??? }; class iterator : public boost::iterator_facade< iterator // Derived , ????? // Base , ????? // Value , boost::?????? // CategoryOrTraversal > { }; };

    Read the article

  • fail-fast iterator

    - by joy
    I get this definition : As name suggest fail-fast Iterators fail as soon as they realized that structure of Collection has been changed since iteration has begun. what it mean by since iteration has begun? is that mean after Iterator it=set.iterator() this line of code? public static void customize(BufferedReader br) throws IOException{ Set<String> set=new HashSet<String>(); // Actual type parameter added **Iterator it=set.iterator();**

    Read the article

  • Custom iterator for a class based on two sets

    - by Dan Hook
    I have a class that contains two sets. They both contain the same key type but have different compare operations. I would like to provide an iterator for the class that iterates through the elements of both sets. I want to start with one set, then when I increment an iterator pointing to the last element of the first set, I want to go to the first element of the second set. How do I do this? I would like to preserve the bidirectional iterator semantics of std::set, but if it turns out that implementing a forward iterator is much easier, so be it. I'm willing to use the Boost Iterator library if that would help.

    Read the article

  • C++ vector<T>::iterator operator +

    - by Tom
    Hi, Im holding an iterator that points to an element of a vector, and I would like to compare it to the next element of the vector. Here is what I have Class Point{ public: float x,y; } //Somewhere in my code I do this vector<Point> points = line.getPoints(); foo (points.begin(),points.end()); where foo is: void foo (Vector<Point>::iterator begin,Vector<Point>::iterator end) { std::Vector<Point>::iterator current = begin; for(;current!=end-1;++current) { std::Vector<Point>::iterator next = current + 1; //Compare between current and next. } } I thought that this would work, but current + 1 is not giving me the next element of the vector. I though operator+ was the way to go, but doesnt seem so. Is there a workaround on this? THanks

    Read the article

  • How to provide stl like container with public const iterator and private non-const iterator?

    - by WilliamKF
    Hello, I am deriving a class privately from std::list and wish to provide public begin() and end() for const_iterator and private begin() and end() for just plain iterator. However, the compiler is seeing the private version and complaining that it is private instead of using the public const version. I understand that C++ will not overload on return type (in this case const_iterator and iterator) and thus it is choosing the non-const version since my object is not const. Short of casting my object to const before calling begin() or not overloading the name begin is there a way to accomplish this? I would think this is a known pattern that folks have solved before and would like to follow suit as to how this is typically solved. class myObject; class myContainer : private std::list<myObject> { public: typedef std::list<myObject>::const_iterator myContainer::const_iterator; private: typedef std::list<myObject>::iterator myContainer::iterator; public: myContainer::const_iterator begin() const { return std::list<myObject>::begin(); } myContainer::const_iterator end() const { return std::list<myObject>::end(); } private: myContainer::iterator begin() { return std::list<myObject>::begin(); } myContainer::iterator end() { return std::list<myObject>::end(); } }; void myFunction(myContainer &container) { myContainer::const_iterator aItr = container.begin(); myContainer::const_iterator aEndItr = container.end(); for (; aItr != aEndItr; ++aItr) { const myObject &item = *aItr; // Do something const on container's contents. } } The error from the compiler is something like this: ../../src/example.h:447: error: `std::_List_iterator<myObject> myContainer::begin()' is private caller.cpp:2393: error: within this context ../../src/example.h:450: error: `std::_List_iterator<myObject> myContainer::end()' is private caller.cpp:2394: error: within this context Thanks. -William

    Read the article

  • Iterator performance contract (and use on non-collections)

    - by polygenelubricants
    If all that you're doing is a simple one-pass iteration (i.e. only hasNext() and next(), no remove()), are you guaranteed linear time performance and/or amortized constant cost per operation? Is this specified in the Iterator contract anywhere? Are there data structures/Java Collection which cannot be iterated in linear time? java.util.Scanner implements Iterator<String>. A Scanner is hardly a data structure (e.g. remove() makes absolutely no sense). Is this considered a design blunder? Is something like PrimeGenerator implements Iterator<Integer> considered bad design, or is this exactly what Iterator is for? (hasNext() always returns true, next() computes the next number on demand, remove() makes no sense). Similarly, would it have made sense for java.util.Random implements Iterator<Double>? Should a type really implement Iterator if it's effectively only using one-third of its API? (i.e. no remove(), always hasNext())

    Read the article

  • Accept templated parameter of stl_container_type<string>::iterator

    - by Rodion Ingles
    I have a function where I have a container which holds strings (eg vector<string>, set<string>, list<string>) and, given a start iterator and an end iterator, go through the iterator range processing the strings. Currently the function is declared like this: template< typename ContainerIter> void ProcessStrings(ContainerIter begin, ContainerIter end); Now this will accept any type which conforms to the implicit interface of implementing operator*, prefix operator++ and whatever other calls are in the function body. What I really want to do is have a definition like the one below which explicitly restricts the amount of input (pseudocode warning): template< typename Container<string>::iterator> void ProcessStrings(Container<string>::iterator begin, Container<string>::iterator end); so that I can use it as such: vector<string> str_vec; list<string> str_list; set<SomeOtherClass> so_set; ProcessStrings(str_vec.begin(), str_vec.end()); // OK ProcessStrings(str_list.begin(), str_list.end()); //OK ProcessStrings(so_set.begin(), so_set.end()); // Error Essentially, what I am trying to do is restrict the function specification to make it obvious to a user of the function what it accepts and if the code fails to compile they get a message that they are using the wrong parameter types rather than something in the function body that XXX function could not be found for XXX class.

    Read the article

  • vector iterator not dereferencable at runtime on a vector<vector<vector<A*>*>*>

    - by marouanebj
    Hi, I have this destructor that create error at runtime "vector iterator not dereferencable". The gridMatrix is a std::vector<std::vector<std::vector<AtomsCell< Atom<T> * > * > * > * > I added the typename and also the typedef but I still have the error. I will move for this idea of vect of vect* of vect* to use boost::multi_array I think, but still I want to understand were this is wrong. /// @brief destructor ~AtomsGrid(void) { // free all the memory for all the pointers inside gridMatrix (all except the Atom<T>* ) //typedef typename ::value_type value_type; typedef std::vector<AtomsCell< Atom<T>* >*> std_vectorOfAtomsCell; typedef std::vector<std_vectorOfAtomsCell*> std_vectorOfVectorOfAtomsCell; std_vectorOfAtomsCell* vectorOfAtomsCell; std_vectorOfVectorOfAtomsCell* vectorOfVecOfAtomsCell; typename std_vectorOfVectorOfAtomsCell::iterator itSecond; typename std_vectorOfVectorOfAtomsCell::reverse_iterator reverseItSecond; typename std::vector<std_vectorOfVectorOfAtomsCell*>::iterator itFirst; //typename std::vector<AtomsCell< Atom<T>* >*>* vectorOfAtomsCell; //typename std::vector<std::vector<AtomsCell< Atom<T>* >*>*>* vectorOfVecOfAtomsCell; //typename std::vector<std::vector<AtomsCell< Atom<T>* >*>*>::iterator itSecond; //typename std::vector<std::vector<AtomsCell< Atom<T>* >*>*>::reverse_iterator reverseItSecond; //typename std::vector<std::vector<std::vector<AtomsCell< Atom<T>* >*>*>*>::iterator itFirst; for (itFirst = gridMatrix.begin(); itFirst != gridMatrix.end(); ++itFirst) { vectorOfVecOfAtomsCell = (*itFirst); while (!vectorOfVecOfAtomsCell->empty()) { reverseItSecond = vectorOfVecOfAtomsCell->rbegin(); itSecond = vectorOfVecOfAtomsCell->rbegin().base(); vectorOfAtomsCell = (*itSecond); // ERROR during run: "vector iterator not dereferencable" // I think the ERROR is because I need some typedef typename or template ???!!! // the error seems here event at itFirst //fr_Myit_Utils::vectorElementDeleter(*vectorOfAtomsCell); //vectorOfVecOfAtomsCell->pop_back(); } } fr_Myit_Utils::vectorElementDeleter(gridMatrix); } If someone want the full code that create the error I'm happy to give it but I do not think we can attach file in the forum. BUT still its is not very big so if you want it I can copy past it here. Thanks

    Read the article

  • What to do of exceptions when implementing java.lang.Iterator

    - by Vincent Robert
    The java.lang.Iterator interface has 3 methods: hasNext, next and remove. In order to implement a read-only iterator, you have to provide an implementation for 2 of those: hasNext and next. My problem is that these methods does not declare any exceptions. So if my code inside the iteration process declares exceptions, I must enclose my iteration code inside a try/catch block. My current policy has been to rethrow the exception enclosed in a RuntimeException. But this has issues because the checked exceptions are lost and the client code no longer can catch those exceptions explicitly. How can I work around this limitation in the Iterator class? Here is a sample code for clarity: class MyIterator implements Iterator { @Override public boolean hasNext() { try { return implementation.testForNext(); } catch ( SomethingBadException e ) { throw new RuntimeException(e); } } @Override public boolean next() { try { return implementation.getNext(); } catch ( SomethingBadException e ) { throw new RuntimeException(e); } } ... }

    Read the article

  • How to use iterator in nested arraylist

    - by Muhammad Abrar
    I am trying to build an NFA with a special purpose of searching, which is totally different from regex. The State has following format class State implements List{ //GLOBAL DATA static int depth; //STATE VALUES String stateName; ArrayList<String> label = new ArrayList<>(); //Label for states //LINKS TO OTHER STATES boolean finalState; ArrayList<State> nextState ; // Link with multiple next states State preState; // previous state public State() { stateName = ""; finalState = true; nextState = new ArrayList<>(); } public void addlabel(String lbl) { if(!this.label.contains(lbl)) this.label.add(lbl); } public State(String state, String lbl) { this.stateName = state; if(!this.label.contains(lbl)) this.label.add(lbl); depth++; } public State(String state, String lbl, boolean fstate) { this.stateName = state; this.label.add(lbl); this.finalState = fstate; this.nextState = new ArrayList<>(); } void displayState() { System.out.print(this.stateName+" --> "); for(Iterator<String> it = label.iterator(); it.hasNext();) { System.out.print(it.next()+" , "); } System.out.println("\nNo of States : "+State.depth); } Next, the NFA class is public class NFA { static final String[] STATES= {"A","B","C","D","E","F","G","H","I","J","K","L","M" ,"N","O","P","Q","R","S","T","U","V","W","X","Y","Z"}; State startState; State currentState; static int level; public NFA() { startState = new State(); startState = null; currentState = new State(); currentState = null; startState = currentState; } /** * * @param st */ NFA(State startstate) { startState = new State(); startState = startstate; currentState = new State(); currentState = null; currentState = startState ; // To show that their is only one element in NFA } boolean insertState(State newState) { newState.nextState = new ArrayList<>(); if(currentState == null && startState == null ) //if empty NFA { newState.preState = null; startState = newState; currentState = newState; State.depth = 0; return true; } else { if(!Exist(newState.stateName))//Exist is used to check for duplicates { newState.preState = currentState ; currentState.nextState.add(newState); currentState = newState; State.depth++; return true; } } return false; } boolean insertState(State newState, String label) { newState.label.add(label); newState.nextState = null; newState.preState = null; if(currentState == null && startState == null) { startState = newState; currentState = newState; State.depth = 0; return true; } else { if(!Exist(newState.stateName)) { newState.preState = currentState; currentState.nextState.add(newState); currentState = newState; State.depth++; return true; } else { ///code goes here } } return false; } void markFinal(State s) { s.finalState = true; } void unmarkFinal(State s) { s.finalState = false; } boolean Exist(String s) { State temp = startState; if(startState.stateName.equals(s)) return true; Iterator<State> it = temp.nextState.iterator(); while(it.hasNext()) { Iterator<State> i = it ;//startState.nextState.iterator(); { while(i.hasNext()) { if(i.next().stateName.equals(s)) return true; } } //else // return false; } return false; } void displayNfa() { State st = startState; if(startState == null && currentState == null) { System.out.println("The NFA is empty"); } else { while(st != null) { if(!st.nextState.isEmpty()) { Iterator<State> it = st.nextState.iterator(); do { st.displayState(); st = it.next(); }while(it.hasNext()); } else { st = null; } } } System.out.println(); } /** * @param args the command line arguments */ /** * * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here NFA l = new NFA(); State s = new State("A11", "a",false); NFA ll = new NFA(s); s = new State("A111", "a",false); ll.insertState(s); ll.insertState(new State("A1","0")); ll.insertState(new State("A1111","0")); ll.displayNfa(); int j = 1; for(int i = 0 ; i < 2 ; i++) { int rand = (int) (Math.random()* 10); State st = new State(STATES[rand],String.valueOf(i), false); if(l.insertState(st)) { System.out.println(j+" : " + STATES[rand]+" and "+String.valueOf(i)+ " inserted"); j++; } } l.displayNfa(); System.out.println("No of states inserted : "+ j--); } I want to do the following This program always skip to display the last state i.e. if there are 10 states inserted, it will display only 9. In exist() method , i used two iterator but i do not know why it is working I have no idea how to perform searching for the existing class name, when dealing with iterators. How should i keep track of current State, properly iterate through the nextState List, Label List in a depth first order. How to insert unique States i.e. if State "A" is inserted once, it should not insert it again (The exist method is not working) Best Regards

    Read the article

  • Modify iterator

    - by isola009
    I have a iterator (ite) created from a set (a): var a = Set(1,2,3,4,5) var ite = a.iterator If I remove 2 element of my set: a -= 2 Now, if I move iterator for all elements, I get all elements (2 element included). It's ok, but... How I can tell to iteratator to delete 2 element?

    Read the article

  • Iterator category

    - by Knowing me knowing you
    In code: //I know that to get this effect (being able to use it with std algorithms) I can inherit like I did in line below: class Iterator //: public std::iterator<std::bidirectional_iterator_tag,T> { private: T** itData_; public: //BUT I WOULD LIKE TO BE ABLE TO DO IT BY HAND AS WELL typedef std::bidirectional_iterator_tag iterator_category; typedef T* value_type;//SHOULD IT BE T AS value_type or T*? typedef std::ptrdiff_t difference_type; typedef T** pointer;//SHOULD IT BE T* AS pointer or T**? typedef T*& reference;//SHOULD IT BE T& AS reference or T*&? }; Basically what I'm asking is if I have my variable of type T** in iterator class is it right assumption that value type for this iterator will be T* and so on as I described in comments in code, right next to relevant lines. Thank you.

    Read the article

  • Why is comparing against "end()" iterator legal?

    - by sharptooth
    According to C++ standard (3.7.3.2/4) using (not only dereferencing, but also copying, casting, whatever else) an invalid pointer is undefined behavior (in case of doubt also see this question). Now the typical code to traverse an STL containter looks like this: std::vector<int> toTraverse; //populate the vector for( std::vector<int>::iterator it = toTraverse.begin(); it != toTraverse.end(); ++it ) { //process( *it ); } std::vector::end() is an iterator onto the hypothetic element beyond the last element of the containter. There's no element there, therefore using a pointer through that iterator is undefined behavior. Now how does the != end() work then? I mean in order to do the comparison an iterator needs to be constructed wrapping an invalid address and then that invalid address will have to be used in a comparison which again is undefined behavior. Is such comparison legal and why?

    Read the article

  • How to correctly inherit std::iterator.

    - by Knowing me knowing you
    Guys if I have class like below: template<class T> class X { T** myData_; public: class iterator : public iterator<random_access_iterator_tag,/*WHAT SHALL I PUT HERE? T OR T** AND WHY?*/> { T** itData_;//HERE I'M HAVING THE SAME TYPE AS MAIN CLASS ON WHICH ITERATOR WILL OPERATE }; }; Questions are in code next to appropriate lines. Thank you.

    Read the article

  • Java LinkedList iterator being exhausted prematurely

    - by Sujeet
    I am using LinkedList and retrieving an Iterator object by using list.iterator(). After that, I am checking it.hasNext(), real issue is while checking it.hasNext(), sometimes it returns false. I need help why this is happening, though I have elements in the list. Some code: public synchronized void check(Object obj) throws Exception { Iterator itr = list.iterator(); while(itr.hasNext()) { //This Line I get false.. though i have list size is 1 Item p = (Item)itr.next(); if(p.getId() == null) {continue;} if(p.getId().getElemntId() == obj.getId() || obj.getId() == 0 ) { p.setResponse(obj); notifyAll(); return; } } Log.Error("validate failed obj.getId="+obj.getId()+" **list.size="+list.size()*This shows 1*); throw new Exception("InvalidData"); }

    Read the article

  • Output iterator's value_type

    - by wilhelmtell
    The STL commonly defines an output iterator like so: template<class Cont> class insert_iterator : public iterator<output_iterator_tag,void,void,void,void> { // ... Why do output iterators define value_type as void? It would be useful for an algorithm to know what type of value it is supposed to output. For example, a function that translates a URL query "key1=value1&key2=value2&key3=value3" into any container that holds key-value strings elements. template<typename Ch,typename Tr,typename Out> void parse(const std::basic_string<Ch,Tr>& str, Out result) { std::basic_string<Ch,Tr> key, value; // loop over str, parse into p ... *result = typename iterator_traits<Out>::value_type(key, value); } The SGI reference page of value_type hints this is because it's not possible to dereference an output iterator. But that's not the only use of value_type: I might want to instantiate one in order to assign it to the iterator.

    Read the article

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