FAQ Database Discussion Community


Efficient way to delete a value from an unordered_map, when given just the value C++

c++,iterator,unordered-map
I have an abstract class called Object and I am using std::unordered_map<int, Object*> objects to contain these Objects within a class called DataSet. Each object has an id associated with it. Normally, when deleting an object from my unordered_map, I can just do iterator = find(id) and then call erase...

Can I extend Iterator to allow access to encapsulated inner class fields?

java,iterator,abstract-class,inner-classes,extends
I'm frustrated, trying to add methods to a custom iterator. For an assignment in my second quarter Java class, we are supposed to implement, from scratch, a linked list. No problem: I have created an outer class to implement the linked list and a static private inner class to implement...

Custom doubly linked list iterator

c++,iterator
So as the title suggests, I've made my own template for an iterator which looks like this: template <class Element> class IteratorDL { private: DoubleNode<Element> *current; public: IteratorDL(DoublyList<Element>); ~IteratorDL(); void next(); void back(); bool isValid(); Element getCurrent(); }; template <class Element> IteratorDL<Element>::IteratorDL(DoublyList<Element> dl) { current = dl.first; cout << current->info;...

Iterating through multiple levels of Child Objects

c#,unity3d,iterator
I have this block of code. And I need to iterate through every child object, but child objects could have more children within them. The Awake() method is called when the program is first ran. So, I'm asking how to build an iterator that will check if there are children...

c++ : double iteration through map

c++,dictionary,iterator
I would like to iterate through a map but the inner loop would just iterate through the upper part of the elements. With a vector it would look like that : for(auto element1 = myVector.begin() ; element1 != myVector.end() ; ++element1){ for(auto element2 = element1 + 1; element2 != myVector.end()...

How to use const InputIterators to write a function for generic containers?

c++,c++11,stl,iterator,const
I'm trying to understand how to write a (stand-alone)function that takes const InputIterators and does something simple while iterating over every element in the container. For simplicity, I'm considering a simple print function, that would print all elements in the range between [first..last), but the function is not allowed to...

Implementing Iterator interface with exception handling

java,unit-testing,iterator,bufferedreader,factory-pattern
I need to create a class library which enables me to read different files (.dat-files with different data representations inside them) and create objects with their content (for every line one object). I also have to create a unit test which starts the reading of the file, so I dont...

Scala: behavior of filter on Iterator vs. List

list,scala,filter,iterator
$ scala Welcome to Scala version 2.10.4 (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0_79). Type in expressions to have them evaluated. Type :help for more information. scala> Iterator(2,4,6) res0: Iterator[Int] = non-empty iterator scala> res0.filter filter filterNot scala> res0.filter def filter(p: A => Boolean): Iterator[A] // Given this definition of...

Convert list of Option to list of T when T cannot be copied

iterator,rust,optional
How do I take a Vec<Option<T>>, where T cannot be copied and unwrap all the Some values? I run in to the error cannot move out of borrowed content when in the map step. I'm happy to move ownership of the original list and "throw away" the Nones. #[derive(Debug)] struct...

Do I really need to implement iterator in that case?

java,collections,iterator
I need some advice about usage of Iterable<T> in Java. I have the following class: public abstract class Validator implements Comparable<Validator>{ public abstract boolean validate(); public abstract int getPriority(); @Override public int compareTo(Validator o) { return getPriority() > o.getPriority() ? -1 : getPriority() == o.getPriority() ? 0 : 1; }...

How to convert a vector to string in C++ [closed]

c++,string,vector,iterator,ostream
Suppose I have a vector<int> and I want to convert it into string, what should I do? What I got from searching on the internet is std::ostringstream oss; if (!vec.empty()) { // Convert all but the last element to avoid a trailing "," std::copy(vec.begin(), vec.end()-1, std::ostream_iterator<int>(oss, ",")); // Now add...

Custom iterator for multiple containers in C++

c++,iterator,containers
I have a pure abstract class and two derived classes that I use to store the same kind of data, let's say int, but in different data structures, let's say a map and a vector. class AbstractContainer { public: virtual MyIterator firstValue() = 0; } class ContainerMap : public AbstractContainer...

Correct type declaration for method returning iterator to C array

c++,arrays,types,iterator,declaration
I can iterate through a C-style array this way: char foo[3] = { 'a', 'b', 'c' }; for (auto it = std::begin(foo); it != std::end(foo); ++it) { *it = 'k'; //values of foo are correctly modified } Now suppose I want to wrap the array inside a class, and expose...

Should Iterator or Iterable be used when exposing internal collection items?

java,arraylist,iterator,iterable,copyonwritearraylist
I have a class with a private mutable list of data. I need to expose list items given following conditions: List should not be modifiable outside; It should be clear for developers who use getter function that a list they get can not be modified. Which getter function should be...

parsing fails when using istream iterator

c++,parsing,stl,iterator,boost-spirit
I'm using boost::spirit to parse csv input (please don't suggest an alternative, this is just testing). When I read the contents of stdin to a string and iterate over that, the parsing succeeds; however, when the contents of std::cin are read directly (through a wrapper that I wrote myself because...

Multimap Iterator retrieve multiple values in Java [closed]

java,iterator,multimap
Is there a way to access each value to assign it to a variable from a java MultiValueMap from Apache commons while iterating? I have one key and two possible values that I would like to extract each iteration that are later written to a table. Currently the below produces...

find out if the `in` operator can be used

python,iterator,containers
What is the simplest (and most elegant) way, to find out if the in operator can be used in python? If I open a python shell and type in: "" in 2 it prints: Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: argument of type 'int'...

What does this function do? (Python iterators)

python,iterator
def partition(n, iterable): p = izip_longest(*([iter(iterable)] * n)) r = [] for x in p: print(x) #I added this s = set(x) s.discard(None) r.append(list(s)) return r This is actually in a job posting on SO and being a newbie I thought it was interesting. So you get output like the...

Trying to remove vector pointer duplicates. Why can't I use .erase()?

c++,class,pointers,vector,iterator
I've got a vector of pointers for my "Faction" class, stored in such a way: vector<Faction *> factionptr_; At this point, I am already able to sort my vector in alphabetical order, so I figured I could use this code here to remove any duplicates that'd show up next to...

Requirements for forward iterator iterator_traits::reference

c++,iterator
I'm trying to figure out exactly what requirements are made on forward_iterators' reference types. In the obvious cases you'll have value_type = T; and reference = T&;. Reading the cppreference page on forward iterator requirements, I saw Expression Return Equivalent expression *i++ reference value_type& temp=*i; ++i; return temp; std::vector<bool> shows...

Nested Vector Iterator - Displaying n'th Vector Only

c++,vector,stl,iterator
Please bear with me if the answer to this is blindingly obvious, I'm pretty new to the STL. So what I have is a nested vector. The iterator works as expected, displaying the values stored in each vector in the nested vector sequentially. My question is, would there be any...

Python access mother class fields

python,tree,iterator,instance
While writing an iterator for a tree class in python I stumbled upon the issue, that I apparently cannot access fields and methods of the mother class without instanciating an iterator instance with a reference to an already existing Tree instance, so I always need to call the iterator like...

Get next item in array using iterator using flags

javascript,jquery,loops,iterator,iteration
I am trying to obtain the next object in an object of objects (is you get my drift). I'm looking through the a list of songs, and trying to determine the next song to play. I use the flag playing to check if the song is being played, then i...

Debug error: Vector iterator not dereferencable and Vector subscript out of range [closed]

c++,vector,stl,iterator
I am trying to implement Rateless codes, but I have some issues in decoding. In the first implementation I used iterator to loop over a vector of vector and do some operation (like erase()) but I was getting this debug error: Vector iterator not dereferencable. After some googling I found...

I can't find imap() in itertools in Python

python,iterator
I have a problem that I want to solve with itertools.imap(). However, after I imported itertools in IDLE shell and called itertools.imap(), the IDLE shell told me that itertools doesn't have attribute imap. What's going wrong? >>> import itertools >>> dir(itertools) ['__doc__', '__loader__', '__name__', '__package__', '__spec__', '_grouper', '_tee', '_tee_dataobject', 'accumulate',...

Is there a built-in way to compare two Iterators?

iterator,rust
I've written the following function to compare two iterators, element-by-element. However, it would be great if I could just reuse something in the standard library. fn iter_eq<A, B, T, U>(mut a: A, mut b: B) -> bool where A: Iterator<Item=T>, B: Iterator<Item=U>, T: PartialEq<U>, { loop { match (a.next(), b.next())...

Joining (union) of Sets inside a Set in Java

iterator,set,java-7,java-api,set-union
I have a map where the values are sets of integers. What i'd want to do is to get in the best way possible (using only the Java API would be great) the union of all the sets of Integers. Map<Long, Set<Integer>> map; What I thought so far is to...

Printing values using Iterator on 2d vector

c++,vector,stl,iterator
Here is my code: std::vector< std::vector<std::shared_ptr<int>> > om(2, std::vector<std::shared_ptr<int>>(2)); om[0][0] = std::shared_ptr<int>(std::make_shared<int>(1)); om[0][1] = std::shared_ptr<int>(std::make_shared<int>(2)); om[1][0] = std::shared_ptr<int>(std::make_shared<int>(3)); //init values om[1][1] = std::shared_ptr<int>(std::make_shared<int>(4)); std::vector<std::shared_ptr<int>>::iterator pd; //inner iterator...

Does const containers have only const iterator?

c++,stl,iterator,standard-library
Why do const STL containers only return const_iterators? For example both std::vector and std::list have the method begin overloaded as: iterator begin(); const_iterator begin() const; const_iterator cbegin() const; I thought I could still modify values of a const vector but not the vector itself. According to the standard library there...

How to create my own array in Ruby

ruby,iterator
a = MyArray.new(3){ |i| (i+1).to_s } a << 1 puts " #{a.size} #{a[1]} #{a.first} " b = MyArray.new; b.push("a").push("b") a += b and my own a.ok("foo") own variable a.nowy etc. How to create array class with my own variables and methods and with all the methods of array: [] each...

Error in finding object in vector

c++,vector,iterator
I have a Point class where I create each object by doing Point p(a, b) and I want to find whether the Point exists in a vector that I declared as vector<Point> vPoint. A segment of my code is as follows; Point p(a, b); vector<Point>::iterator it = find(vPoint.begin(), vPoint.end(), p);...

Iterator Java to store object

java,iterator
I need to store objects using iterator but I found just the last element, what do you think ? if (links.size()>0) { for (Iterator<Link> iterator = links.iterator(); iterator.hasNext();) { Link link = (Link) iterator.next(); item.setLink(link); objects.add(item); } } In objects, I pass to item and I found the last link,...

Why is it.current changing his values during debug?

c#,iterator,ienumerable,enumerator
I'm trying to get an element at a specific index with the method : public T GetElem(int index) { var it = outerInstance.iterator(); var i = 0; while (it.MoveNext() && i < index) { i++; } return it.Current; } I have created my own iterator which is an internal class...

In python, can I lazily generate copies of an iterator using tee?

python,iterator,lazy-evaluation
I'm trying to create an iterator which lazily creates (potentially infinitely many) copies of an iterator. Is this possible? I know I can create any fixed finite number of copies by simply doing iter_copies = tee(my_iter, n=10) but this breaks down if you don't know n ahead of time or...

Recursive iterator for composite pattern

java,iterator,composite
I have the tree classes AbstractComponent, Leaf and Composite: public abstract class AbstractComponent { privavte String name; [...] } public class Leaf extends AbstractComponent { [...] } public Composite extends AbstractComponent { private List<AbstractComponent> children; public void addChild(AbstractComponent a) { [...] } public List<AbstractComponent> getChildren() { return children; } }...

Java - How to check if an object is an instance of a class in the class definition

java,iterator,composite,iterable
Code: public class Composite extends Component implements Iterable<Component>{ private List<Component> caseComponents = new ArrayList<Component>(); @Override public Iterator<Component> iterator(){ return new CompIterator(); } private class CompIterator implements Iterator{ int index = 0; @Override public boolean hasNext(){ if(index<caseComponents.size()){ return true; } return false; } @Override public Object next() { if(this.hasNext()){ return caseComponents.get(index++);...

Iterating through a list searching for duplicates

java,list,collections,iterator
So I have this task that I must do a dice roller and then search for a certain combination if it was rolled. I have an overriden equals method, that checks for the combination and it is working properly. Every object from the class Dice has its own string array...

Insert items into an array while iterating

arrays,ruby,iterator
How would I modify (add/remove elements) an array while iterating over it and have the iterator be aware of it? For example I would think this code: a = "1234567890".split("") a.each_with_index{|d, i| if d.eql?('5') a.delete_at(i) a.insert(i, ['A', 'B', 'C'] ) end print d } would produce: 1234ABC67890 but instead produces...

Using vector std::find with a user-created object - third argument

c++,stl,iterator,find
I am trying to make use of std::find to search a vector and return an iterator of the required object is found. The problem I am having is that I am not sure what to put as the third argument. Below is the relevant line of code as well as...

Using to dynamically build element's name

jsp,struts2,iterator,ognl,struts-tags
I want to reuse a set of HTML field elements and have struts build 'name' attributes from a variable. I saw this How To Generate unique HTML id attributes within Struts 2 iterator tag and figured I could use something similar but can't get it to work. It seems I...

Why does the Iterator not “Move Next” in a for loop

java,iterator
I'm learning to iterate, and have implemented an Iterator on my 'CStickChart' Class using the following private property: private List<CStick> cStickCollection = new ArrayList<CStick>(); and then implementing the method to return CSticks: public Iterator<CStick> iterator() { return this.cStickCollection.iterator(); } Now when I try and iterate through it, I'm able to...

how to iterate on a table in sql server for the same id in many rows?

sql-server,loops,iterator
I have a table called city and table called routes_. the relation between them is many to many so i used a table called map between them. routes_ table has the names of the routes city table has the cordinates of city. map table has all the cities for each...

Passing iterator's element to a function: wrong type of pointer

c++,pointers,stl,iterator
I'm attempting to solve Project Euler's problem #3 using C++ to gain an understanding of how to use C++ iterators. According to the examples I've seen online, I can use the dereferened iterator as a parameter for cout, and it will print the elements successfully. By that same logic, I...

Is there a conventional iterator interface in Java which separates traversal from element access?

java,iterator
For my application, element access is expensive, so java.util.Iterator is no use. I want something more like C++ iterators, where I can move the pointer around without returning an element. Is there something in the standard library like this, or has some de facto standard interface evolved through custom? (If...

Filter vector in place

iterator,rust
In Rust is it possible to operate on a vector in-place? I'd like to remove some elements from a Vec, but vec.iter().filter().collect() creates a new vector with borrowed items. I'd like to mutate the original Vec without extra memory allocation (and keep memory of removed elements as an extra capacity...

Using Iterators on a list of pointers

c++,list,iterator,operator-precedence
I am trying to iterator over a list of pointers: int main () { list<Game*> Games; Games = build_list_from_file(); //Reading the games.info file list<Game*>::iterator it = Games.begin(); it++; cout << *it->get_name() << endl ; // ... } When I compile it, I have this error: error: request for member ‘get_name’...

Append Loop Variable to Variable Name

c#,string,for-loop,iterator,append
I have 5 DataTables that needs to be converted to TXT files. Instead of creating them separately, I thought I use a for loop. Here's my code: StringBuilder sb = new StringBuilder(); for (int i = 1; i < 5; i++) { DataTable dtFile1 = file1BLO.SelectFile1ForCSV() foreach (DataRow dr in...

how to i change mouse pointer to hand signal and change the color of row while mouse go over a row in table

javascript,jquery,ajax,iterator
<logic:iterate name="studentDetails" id="student" indexId="index"> <tr> <td><bean:write name="student" property="name" /></td> <td><bean:write name="student" property="age" /></td> <td><bean:write name="student" property="class" /></td> <td><bean:write name="student" property="mark" /></td> <td><bean:write name="student" property="result" /></td> </tr> </logic:iterate> I want to display all the student details, and...

Using generic iterators instead of specific list types

arrays,vector,iterator,rust
I'm very new to Rust, coming from C# / Java / similar. In C# we have IEnumerable<T> that can be used to iterate almost any kind of array or list. C# also has a yield keyword that you can use to return a lazy list. Here's an example... // Lazily...

Iterator loop does not count the last item

c++,templates,iterator
Assuming the linked list is defined this way: template <typename Object> struct Node{ Object data; Node *prev; Node *next; Node(const Object & d = Object(), Node *p = NULL, Node *n = NULL) : data(d), prev(p),next(n){} }; template <typename Object> class List { public: iterator begin(){return iterator(head->next);} iterator end(){return iterator(tail);}...

Accessing Iterator After Deletion Causes Crash

c++,pointers,crash,iterator
so I'm used to coding in C# and have just started using C++ again after a pretty substantial break. Essentially what I'm trying to do is to create a program that has lists of students with IDs, in courses. I have this code that essentially prints out all available students...

iterating over a table passed as an argument to a function in lua

for-loop,lua,iterator,lua-table
I am trying using the for _ in pairs() notation to iterate over a table within a function, but if I type anything, even gibberish like print('asdgfafs'), nested inside the for loop, it never gets printed. Code: record = {bid1,bid2,bid3} bid1 = {bidTime = 0.05,bidType = 'native'} bid2 = {bidTime...

defining my_each in terms of my_times

ruby,iterator,codeblocks,control-flow,ruby-1.9.1
I'm reading The Well-Grounded Rubyist and have come across an extra credit challenge to which there is no answer. class Array def my_each c = 0 until c == size yield(self[c]) c += 1 end self end end An example is given of creating a my_each with my_times class Array...

Lifetime in Iterator impl

iterator,rust,lifetime
I am having trouble expressing the lifetime of the return value of an Iterator impl. How can I compile this code without changing the return value of the iterator? I'd like it to return a vector of references. Here is the current error returned by the compiler, as far as...

segfault accessing qlist element through an iterator

c++,iterator,qlist
I get a segfault while iterating over a QList. I don't understand what I am doing wrong. I have a QList of Conversation. Inside a Conversation I have a QList of Msg. Below are the class description : Msg class : class Msg { public: Msg(); Msg(const Msg& other); Msg&...

Generate random permutation of huge list (in Python)

python,algorithm,iterator,permutation
I'd like to create a random permutation of the numbers [1,2,...,N] where N is a big number. So I don't want to store all elements of the permutation in memory, but rather iterate over the elements of my particular permutation without holding former values in memory. Any idea how to...

Is C++'s default copy-constructor inherently unsafe? Are iterators fundamentally unsafe too?

c++,iterator,copy-constructor,default-copy-constructor
I used to think C++'s object model is very robust when best practices are followed. Just a few minutes ago, though, I had a realization that I hadn't had before. Consider this code: class Foo { std::set<size_t> set; std::vector<std::set<size_t>::iterator> vector; // ... // (assume every method ensures p always points...

Iterator for an array list of Class

java,collections,iterator,listiterator
Am New to Java so please bear with me if my question seems to be silly. I am learning collections,I have written a program which will store student names id and marks.I am storing all these in a Arraylist. Using for loop I am able to print the values in...

Is there a Java class that lets me iterate trough the last x elements? [duplicate]

java,list,collections,iterator
This question already has an answer here: How to start iterating through ArrayList from set index? [closed] 5 answers I am looking for something like a LinkedList with a function that returns an iterator for the last x elements. For example: LinkedList<Oky> obj; obj.add(a); obj.add(b); obj.add(c, d, e, f,...

Const-correctness of self made iterators

c++,iterator,const-iterator
General goal I manage a collection of objects (Collection of Real as simple example). Then I defined iterators on my collection. That means : iterator, const_iterator, reverse_iterator and const_reverse_iterator. In this example, I will only pay attention on iterator and const_iterator, the two others are very similar. After that, I...

memory error when reading from multiple files

python,memory,iterator,out-of-memory
I am reading in 15 files that are located in a folder on my desktop. I can read in the first few files no problem but when i get a little more into it I end up getting a memory error that looks to be caused by Pythons built in...

How to implement Iterator and IntoIterator for a simple struct?

iterator,rust
Given the following struct: struct Pixel { r: i8, g: i8, b: i8, } How would someone implement the Iterator and IntoIterator traits. I've tried various forms of the following with no success. impl IntoIterator for Pixel { type Item = i8; type IntoIter = Iterator<Item=Self::Item>; pub fn into_iter(self) ->...

How do iterators map/know their current position or element

c++,for-loop,iterator
Consider the following code example : #include <vector> #include <numeric> #include <algorithm> #include <iterator> #include <iostream> #include <functional> int main() { std::vector<int> v(10, 2); std::partial_sum(v.cbegin(), v.cend(), v.begin()); std::cout << "Among the numbers: "; std::copy(v.cbegin(), v.cend(), std::ostream_iterator<int>(std::cout, " ")); std::cout << '\n'; if (std::all_of(v.cbegin(), v.cend(), [](int i){ return i % 2...

Figuring out return type of closure

iterator,rust
I'm having troubles figuring out the type signature of the fn filter function in following example. The Node and Descendant definition is just there for syntax . It's not meant to do anything! use std::iter::Filter; #[derive(Clone)] pub struct Node<'a> { s: &'a str, } pub struct Descendants<'a>{ iter: Node<'a> }...

Return a moving window of elements resulting from an iterator of Vec

iterator,rust
I'm trying to figure out how to return a window of elements from a vector that I've first filtered without copying it to a new vector. So this is the naive approach which works fine but I think will end up allocating a new vector from line 5 which I...

Best way to access vector objects

c++,vector,iterator
If I have a vector, std::vector<int> MyVector; And want to access the n'th element of that vector, I can do so in many different ways: int x = MyVector[n]; or int x = MyVector.at(n); or even using iterators that I am not familiar with. I am sure there are also...

pre/post increment operator on OutputIterator

c++,stl,stream,iterator
I read in an article on OutputIterator that we only can dereference it as lvalue. My question is about operator++ which increments the iterator by one position. So, *it++ = t would be {*it = t; ++it; } https://www.sgi.com/tech/stl/OutputIterator.html Now, I am assuming that operator++ would be overloaded in such...

Iterate through a specific directory tree and store all the .ttf files into an array in PHP

php,loops,iterator,directory,iteration
Lets say I have a lot of files, some of those are in these paths: root/fonts/folder1/font1.ttf root/fonts/folder1/font2.ttf root/fonts/folder2/font1.ttf root/fonts/folder2/font2.ttf root/scripts/file.php Remember that there are also other types of files in those folders. How can my "/scripts/file.php" iterate through the "../fonts/" directory tree and store all the TrueType font (.ttf) files...

Autocreate nested foreach statement

c#,selenium-webdriver,foreach,iterator,auto
I have a simple scenario I am trying to workout which involves auto creating nested foreach statements. What the method is to do is take the int value passed into the method and based on this, it should automatically create nested foreach statements. public static String[] ValuesAdd1 = { "a",...

For-Each Loop Alternative - Clarification

java,loops,foreach,iterator
I am working through lessons in Java, and have not been able to completely understand what is going on in the following lesson. Purpose: The purpose of this lesson is to explain how a for-each loop works by creating an alternative that simulates how the for-each loop would work. In...

When writing a custom iterator, how can I avoid the compiler generating a Reset() method that throws an exception?

c#,exception,iterator
I have coded a custom iterator as a workaround to a complex COM Interop issue. The iterator is about as simple as it gets: public IEnumerator GetEnumerator() { yield return DriveRates.driveSidereal; yield return DriveRates.driveKing; yield return DriveRates.driveLunar; yield return DriveRates.driveSolar; } DriveRates is an enum. My understanding is that the...

Generate different period of time using joda

java,loops,datetime,iterator,jodatime
I have a scenario to generate specific time between two dates. Let's say Mar 1st to Mar 31st as my input. I need to generate datetime with specific hours as below. Mar 1st 03:00 - Mar 1st 06:59 Mar 1st 07:00 - Mar 1st 14:59 Mar 1st 15:00 - Mar...

Javascript iterator in return statement

javascript,iterator
I've been studying javascript examples and I came across this: var numb=1; function funName(numb){ // function work return numb+1; } In this example I'm not sure how the number is iterating each time on return numb+1; I thought it would have to look more like numb=numb+1; Does this just work...

STL Map - Displaying what is pointed to by find() function

c++,dictionary,stl,iterator,iostream
For testing purposes, I'm running the following code through a for loop. Only the first three keys actually exist, and "Record found" is displayed as expected, along with the key, retrieved from findVertex->first. My question is, how would I be able to access the second value being pointed to? findVertex->secondseems...

Performance of iterator function next() vs. advance() in for-loops

c++,list,opencv,iterator
is there any difference in performance between next() and advance()? I am asking as my code is very slow and I try to figure out why. I go through several lists of different types and use a for loop where I update three different iterators. The code looks something like...

Java - Create sublist from a list based on suffix

java,arraylist,collections,iterator,sublist
I'm trying to create sublists from a list based on the suffix. public class Test { public static void main(String args[]) { List<List<String>> subList = new ArrayList<List<String>>(); List<String> myList = new ArrayList<String>(); myList.add("Text_1"); myList.add("XYZ_3"); myList.add("ABC_1"); myList.add("Text_2"); myList.add("Text_3"); myList.add("XYZ_1"); myList.add("XYZ_2"); myList.add("ABC_2"); for (String item : myList) { List<String> tempList = new...

Iterate vector inside method

c++,templates,iterator
I am currently learning C++ , and I have following working code: int main(int argc, char** argv) { map<unsigned int, list<mpz_class>> otp; // ..... for(auto it1 = otp.begin(); it1 != otp.end(); ++it1) { bool first = true; for(auto it2 = it1->second.begin(); it2 != it1->second.end(); ++it2) { if (!first) { cout...

iterating on a list of vectors of some class (C++)

c++,list,vector,iterator,containers
Can anyone help me with why this code give me a segmentation fault on the inner loop? I am trying to iterate on a list of vectors of some class block. class chain { list<vector<Block*>* >* _blockChain; } Chain* someChain = new Chain(); for(list<vector<Block*>*>::iterator listIter = someChain->getChain()->end() ; listIter !=...

Java , Removing object from ArrayList

java,arraylist,iterator
I have ClassA which has a static ArrayList of Objects public static ArrayList<Meteorit> meteorits = new ArrayList<Meteorit>(); Now I want to remove an object from this list like this ClassA.meteorits.remove(this); This is written in Meteorit class . But it throws exception when I want to use the objects in the...

More Compact List Comprehension Where Iteration Variable is Unused

python,iterator,generator,list-comprehension,generator-expression
I have several sampling functions that need to be called for a certain amount of times as in the following instruction: samples = [do_sampling() for _unused in range(n_samples)] I wonder, is there a more compact way to express that statement, especially by avoiding the _unused variable?...

Using python iterators to recursively list files in a folder

python,iterator,generator
I am trying to list all the TIFF files in a folder using python. I found an answer to this SO question, and adapted its code as follows: import os import glob from itertools import chain def list_tifs_rec(path): return (chain.from_iterable(glob(os.path.join(x[0], '*.tif')) for x in os.walk(path))) def concatStr(xs): return ','.join(str(x) for...

iterating row by row over pandas dataframe with the possibility to jump back

python,pandas,iterator
I know that pandas.DataFrame.iterrows allows to iterate through a DataFrame row by row. Is it possible to jump back in the iteration? For instance, I have a list of ten items. The iteration cursor is at #8. And for some reason i want to jump back to e.g. #5 and...

LinkedList iterator remove

java,linked-list,delete,iterator
I have a question on linkedlist iterator If I'm using next , previous and remove methods for example : name.add("Alvin") name.add("Keven") name.add("Jack") ListIterator<String> iterator = name.listIteraot(); //|AKJ iterator.next(); // A|KJ iterator.next(); // AK|J iterator.add("Nina") // AKN|J iterator.next(); // AKNJ| iterator.remove(); // AKN| In the next and then remove method we...

How to unzip an iterator?

python,iterator,generator,itertools
Given a list of pairs xys, the Python idiom to unzip it into two lists is: xs, ys = zip(*xys) If xys is an iterator, how can I unzip it into two iterators, without storing everything in memory?...

How to change an attribute of an object in a for loop with iterators?

c++,vector,iterator
It's a story about a car entering a queue at an intersection. So, for each road, there are different lanes (iterator it), and for each lanes, there are different cars (iterator it2). void function(Road& R, int timestep) { vector<int> lane = R.void1() { for(vector<int>::iterator it = lane.begin() ; it !=...

Trying to iterate through queue of object pointers in c++

c++,iterator,iteration,deque
I am trying to iterate through a deque of objects of class Node and call the function get_State from each one. The code is as follows: #include <deque> #include <queue> #include <stdlib.h> #include <stdio.h> #include <inttypes.h> #include <assert.h> #include <sys/time.h> #define MAX_LINE_LENGTH 999 class Node { private: state_t base_state, new_state;...

Implementing Iterator for abstractCollection

java,generics,iterator,override,abstract
Hi I want to implement the iterator for a class that extends abstract Collection. class Name<E extends Comparable<E>> extends AbstractCollection<CompRational> implements Iterable<E>{ ... public Iterator<E> iterator(){ return new NameIterator<E>(this); } ... } and the Iterator should look like this class NameIterator<E extends Comparable<E>> implements Iterator<E>{ private Name<E> tree; private int...

File.open('file.txt') vs. File.open('file.txt').readlines

ruby,iterator
I checked using File.open('file.txt').class and File.open('file.txt').readlines.class and the former one returns File and the latter returns Array. I understand this difference, but if I do something like: File.open('file.txt').collect {|l| l.upcase} === File.open('file.txt').readlines.collect {|l| l.upcase} it returns true. So are there any differences between the two objects when each item in...

Copy constructor used in a “for” loop, but where?

c++,constructor,iterator,const,implicit-conversion
I'm writing an UTF-8 string class and it's two const and non-const iterator classes. I'm encountering a const problem. Here are the classes : class Utf8String { public: class ConstIter; class Iter { friend class ConstIter; private: Iter(); private: Utf8String * m_pStr; utf8::iterator< char * > m_oIter; public: Iter( const...

Why is `for i in a` not idiomatic Ruby? [closed]

ruby,for-loop,coding-style,iterator
Ruby has support for the for i in a syntax, but no one really uses it. One of the design principles of Ruby is it's readability, and I find for i in a ... end much more readable (and easier to type) than a.each do |i| ... end Why is...

How can I restart a string iterator endlessly?

python,python-3.x,iterator,generator
This question is somewhat related to this, this, and this one. Assume I have two generators/iterators of different lengths: >>> s = "abcde" >>> r = range(0, 16) I now want to repeat iterating over the shorter one until the longer one is exhausted. The standard zip() function terminates once...

Regex capture iterator method moves iterator

regex,iterator,rust,borrow-checker
I am processing simple strings of the format "1s:1d", "100:5000", etc with this regex: let retention_matcher = regex::Regex::new({r"^(\d+)([smhdy])?:(\d+)([smhdy])?$"}).unwrap(); I know this regex should only match once so I want to run the regex for captures and check the number of captures. let iter = retention_matcher.captures_iter(ts); let count = iter.count(); println!("iter.count():...

Angular only repeats over arrays with no repeated elements [duplicate]

javascript,arrays,angularjs,iterator
This question already has an answer here: Angular ng-repeat Error “Duplicates in a repeater are not allowed.” 3 answers The following Angular code displays four dancing hamsters: <img src="images/dancingHamster.gif" ng-repeat="i in [1,2,3,4]"> whereas this code displays nothing: <img src="images/dancingHamster.gif" ng-repeat="i in [1,1,1,1]"> Here are some more arrays that work:...

Why is ArrayIterator subclass's constructor never called?

php,iterator
I'm baffled why a subclass to ArrayIterator is never getting its __construct method called. Consider this example: <?php class ConstructorException extends Exception {} class Foo extends ArrayObject { function __construct( $arr = array(), $flags = 0, $iterator = 'ArrayIterator' ) { $iterator = 'FooIterator'; parent::__construct( $arr, $flags, $iterator ); }...

Concurrent modification exception when using iterator? (Java)

java,debugging,arraylist,iterator
I am trying to write code for the simulation WaTor in which sharks and fish eat each other and simulate population control etc. Anyways, the problem I am having is that i keep getting a concurrect modification exception even when using an iterator. Here is my code: private void updateSharks()...

upper_bound() gives WRONG output

c++,iterator
My program below reads a text file (data.txt), uses upper_bound() to compare a value but it doesn't give the correct value. I couldn't figure out why the output is always the last value. #include <iostream> #include <vector> #include <algorithm> int main(int argc, char* argv[]) { FILE* textFile; std::string filename; std::vector...

Comparing two string iterators always comes out true C++

c++,string,iterator
So, here's a bit of an odd question that I'm really just having trouble with. I have a list of strings and I'm trying to see if two of them match. So, I have one iterate through and get each string, and another that checks if it has a match....

java - how to create custom hashtable iterator?

java,iterator,hashmap,hashtable,inner-classes
I am currently trying to implement a Hashtable collection--I have everything up and running but I ran into kind of a conceptual problem when I was trying to define a custom iterator for the table. I have an internal class called 'HashEntry' which are the actual objects stored in the...

Python shelve and random iterator

python,iterator,iterable,shelve
I want to create an iterator for a shelve key-value store that can be used multiple times but each time returns values in a different order. A shelve iterator returns values in a random order but the order doesn't change on each invocation. Here is an example: import shelve #...

Write remove method at index based on iterator equivalent from java to c#

java,c#,iterator,sequences
I am trying to write the equivalent method from java. MyIterator extends Iterator. public T remove(int index) { MyIterator<T> it = support.iterator();//returns iterator over my sequence implementation int i = 0; T e = null; while (it.hasNext() && i < index) { e = it.next(); i++; } it.remove(); return e;...