iterator interview questions
Top iterator frequently asked interview questions
I wonder why cbegin
and cend
were introduced in C++11?
What are cases when calling these methods makes a difference from const overloads of begin
and end
?
Source: (StackOverflow)
I have a custom container class for which I'd like to write the iterator
and const_iterator
classes.
I never did this before and I failed to find an appropriate how-to. What are the guidelines regarding iterator creation, and what should I be aware of ?
I'd also like to avoid code duplication (I feel that const_iterator
and iterator
share many things; should one subclass the other ?).
Foot note: I'm pretty sure Boost has something to ease this but I can't use it here, for many stupid reasons.
Source: (StackOverflow)
What is the use of the yield
keyword in Python? What does it do?
For example, I'm trying to understand this code1:
def node._get_child_candidates(self, distance, min_dist, max_dist):
if self._leftchild and distance - max_dist < self._median:
yield self._leftchild
if self._rightchild and distance + max_dist >= self._median:
yield self._rightchild
And this is the caller:
result, candidates = list(), [self]
while candidates:
node = candidates.pop()
distance = node._get_dist(obj)
if distance <= max_dist and distance >= min_dist:
result.extend(node._values)
candidates.extend(node._get_child_candidates(distance, min_dist, max_dist))
return result
What happens when the method _get_child_candidates
is called?
A list is returned? A single element is returned? Is it called again? When will subsequent calls stop?
1. The code comes from Jochen Schulz (jrschulz), who made a great Python library for metric spaces. This is the link to the complete source: Module mspace.
Source: (StackOverflow)
Why does the Iterator
interface not extend Iterable
?
The iterator()
method could simply return this
.
Is it on purpose or just an oversight of Java's designers?
It would be convenient to be able to use a for-each loop with iterators like this:
for(Object o : someContainer.listSomeObjects()) {
....
}
where listSomeObjects()
returns an iterator.
Source: (StackOverflow)
I'm iterating over a vector and need the index the iterator is currently pointing at. AFAIK this can be done in two ways:
it - vec.begin()
std::distance(vec.begin(), it)
What are the pros and cons of these methods?
Source: (StackOverflow)
What is the difference between iterators and generators? Some examples for when you would use each case would be helpful.
Source: (StackOverflow)
Take the following two lines of code:
for (int i = 0; i < some_vector.size(); i++)
{
//do stuff
}
And this:
for (some_iterator = some_vector.begin(); some_iterator != some_vector.end();
some_iterator++)
{
//do stuff
}
I'm told that the second way is preferred. Why exactly is this?
Source: (StackOverflow)
What are the most basic definitions of "iterable", "iterator" and "iteration" in Python?
I've read multiple definitions but their exact meaning still won't sink in.
Can someone please help me with the basic idea?
Source: (StackOverflow)
Should I use
std::sort(numbers.begin(), numbers.end(), std::greater<int>());
or
std::sort(numbers.rbegin(), numbers.rend()); // note: reverse iterators
to sort a vector in descending order? Are there any benefits/drawbacks with one approach or the other?
Source: (StackOverflow)
I am looking for a concise way to convert an Iterator
to a Stream
or more specifically to "view" the iterator
as a stream
.
For performance reason, I would like to avoid a copy of the iterator in a new list:
Iterator<String> sourceIterator = Arrays.asList("A", "B", "C").iterator();
Collection<String> copyList = new ArrayList<String>();
sourceIterator.forEachRemaining(copyList::add);
Stream<String> targetStream = copyList.stream();
Based on the some suggestions in the comments, I have also tried to use Stream.generate
:
public static void main(String[] args) throws Exception {
Iterator<String> sourceIterator = Arrays.asList("A", "B", "C").iterator();
Stream<String> targetStream = Stream.generate(sourceIterator::next);
targetStream.forEach(System.out::println);
}
However, I get a NoSuchElementException
(since there is no invocation of hasNext
)
Exception in thread "main" java.util.NoSuchElementException
at java.util.AbstractList$Itr.next(AbstractList.java:364)
at Main$$Lambda$1/1175962212.get(Unknown Source)
at java.util.stream.StreamSpliterators$InfiniteSupplyingSpliterator$OfRef.tryAdvance(StreamSpliterators.java:1351)
at java.util.Spliterator.forEachRemaining(Spliterator.java:326)
at java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:580)
at Main.main(Main.java:20)
I have looked at StreamSupport
and Collections
but I didn't find anything.
Source: (StackOverflow)
I need to go through a set and remove elements that meet a predefined criteria.
This is the test code I wrote:
#include <set>
#include <algorithm>
void printElement(int value) {
std::cout << value << " ";
}
int main() {
int initNum[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
std::set<int> numbers(initNum, initNum + 10);
// print '0 1 2 3 4 5 6 7 8 9'
std::for_each(numbers.begin(), numbers.end(), printElement);
std::set<int>::iterator it = numbers.begin();
// iterate through the set and erase all even numbers
for (; it != numbers.end(); ++it) {
int n = *it;
if (n % 2 == 0) {
// wouldn't invalidate the iterator?
numbers.erase(it);
}
}
// print '1 3 5 7 9'
std::for_each(numbers.begin(), numbers.end(), printElement);
return 0;
}
At first, I thought that erasing an element from the set while iterating through it would invalidate the iterator, and the increment at the for loop would have undefined behavior. Even though, I executed this test code and all went well, and I can't explain why.
My question:
Is this the defined behavior for std sets or is this implementation specific? I am using gcc 4.3.3 on ubuntu 10.04 (32-bit version), by the way.
Thanks!
Proposed solution:
Is this a correct way to iterate and erase elements from the set?
while(it != numbers.end()) {
int n = *it;
if (n % 2 == 0) {
// post-increment operator returns a copy, then increment
numbers.erase(it++);
} else {
// pre-increment operator increments, then return
++it;
}
}
Edit: PREFERED SOLUTION
I came around a solution that seems more elegant to me, even though it does exactly the same.
while(it != numbers.end()) {
// copy the current iterator then increment it
std::set<int>::iterator current = it++;
int n = *current;
if (n % 2 == 0) {
// don't invalidate iterator it, because it is already
// pointing to the next element
numbers.erase(current);
}
}
If there are several test conditions inside the while, each one of them must increment the iterator. I like this code better because the iterator is incremented only in one place, making the code less error-prone and more readable.
Source: (StackOverflow)
In Python, I would like to get the first item from a list matching a condition. For example, the following function is adequate:
def first(the_iterable, condition = lambda x: True):
for i in the_iterable:
if condition(i):
return i
This function could be used something like this:
>>> first(range(10))
0
>>> first(range(10), lambda i: i > 3)
4
However, I can't think of a good built-in / one-liner to let me do this (and I don't particularly want to copy this function around if I don't have to). Any ideas?
(It's important that the resulting method not process the entire list, which could be quite large.)
Source: (StackOverflow)