15,023 questions
4
votes
5
answers
358
views
Can the hasNext() iterator method return false first and then true?
I want to implement the java.util.Iterator interface for iterating over data retrieved through an external system's API. The data may appear in the external system over time.
Is it correct to return ...
5
votes
1
answer
123
views
Can I safely and portably use iterators when a list is moved?
I couldn't find any wording in the Standard that iterators to list elements continue to be valid when a new list is move-constructed from it, like this:
#include <list>
#include <print>
#...
2
votes
1
answer
170
views
How to avoid iterator invalidation in loop
Question: Is it a don't do it that delete a element of map in a loop?
//std::set<Battle::BattleBuf *> m_bufs;
for (auto& pBuf : m_bufs) {
pBuf->doEffect(pDef, param); // It can a ...
Advice
1
vote
13
replies
93
views
How to create a map-like interface for std::vector, or how to treat a vector as an index-value map?
I do things with maps (could be std::map or another map from the standard library, a boost map, a custom map from another library, etc):
template<class T>
void do_map_stuff(T const& t)
{
...
0
votes
1
answer
105
views
Returning nested Maps and their Closures
I have a custom collection type that
can be somewhat cheaply altered
(think of shifting all values by some offset, creating a new collection)
can do some calculations with respect to some other ...
Best practices
1
vote
7
replies
136
views
Iterator in a doubly linked list in C
Working on an assignment for a Data Structures course I started thinking about some implementation differences for iterators. Working in C. Let's say my iterator looks like this:
struct list_iter {
...
1
vote
1
answer
113
views
How to remove outdated files and empty directories for garbage collection
I'm tweaking a garbage collector class whose job is to iterate through a disk cache of files in subdirs, find any that are "out of date" and remove them. Further, if it finds any empty ...
Best practices
0
votes
4
replies
81
views
In rust, is there an iterator adapter that can consume multiple (but not all) items before producing an output?
I can't help thinking this is not an uncommon idiom and I'm just being an idiot but I've spent ages searching SO and reading the docs for std::iter and for the itertools crate and have got nowhere. ...
1
vote
1
answer
106
views
Make newtype iterable (same as underlying)
I wanted to quickly make an alias type iterable in rust. Here's what I have:
#[derive(Debug, Clone)]
struct SSHDomains
{
hostname: String,
path: String,
}
#[derive(Iter, IntoIter)]
pub struct ...
3
votes
1
answer
83
views
Borrowed value does not live long enough for generic lifetime
The Rust compiler gives me a lifetime error with the following code (which is a minimal working example of some real code):
pub trait TElement: Copy {
// Details irrelevant
}
pub trait TSet<'a,...
3
votes
2
answers
393
views
Is it ok to write `&*string.end()`?
I see many places in public repositories, where the first and last iterators of std::vector/std::string/std::string_view are converted into pointers using the combination of &* operators. In ...
0
votes
0
answers
181
views
Can a segfault occur if you are doing iterator arithmetic ops beyond limits?
it -> a random valid vector iterator
const int kLookAheadIndex -> a random number
auto it_ahead = std::max(it - kLookAheadIndex, path.cbegin()); // get a look-ahead point to look at
I know ...
0
votes
2
answers
152
views
How can I force iterator blocks to validate parameters before packing up and returning as a continuation?
Situation: A method that validates its arguments and returns an iterator;
public static IEnumerable<double> Range(double startingValue, double step, int count)
{
// I would really like this ...
Best practices
0
votes
4
replies
102
views
Iterating over several nested iterators
I have to implement an Iterator<E> that needs to internally iterate through multiple private iterators at different levels. For example, an Iterator<A>, an Iterator<B>, and an ...
2
votes
1
answer
232
views
Are the iterators of `map<key, value, greater<>>` and `map<key, value, less<>>` guaranteed to be the same type?
I have 2 maps
using BidBook = std::map<float, int, std::greater<>>; // price -> qty
using AskBook = std::map<float, int, std::less<>>;
I have a struct that contain iterator ...
Best practices
1
vote
7
replies
187
views
How to best group an iterator's items into batches?
Our program reads results of an SQL query and turns each row into a task for a worker to perform. Something like:
for row in query.results():
cluster.submit(row)
However, most of the tasks are so ...
1
vote
1
answer
127
views
OpenMP in C | How to keep private iterable after loop
So i'm working on some homework related to fixing som buggy code when i ran into an interesting problem. I don't think it was one of the indended bugs because the lecturer was confused by it as well. ...
4
votes
2
answers
135
views
Iterate over elements, not references on them
I am trying to implement a display driver wrapper in (no_std) Rust, that is responsible to write an sequence of pixels into a frame buffer. The pixel data is coming from the C world, and representing ...
0
votes
0
answers
38
views
How do I use str::split and str::split_whitespace in the arms of a match expression in Rust [duplicate]
I have some code that splits a string and then does some processing on each part of the string, before returning Vec of values based on each segment. By default, the code should split the string by ...
1
vote
1
answer
85
views
Shallow copying enumeration iterator behavior in Python
I am trying to understand the behavior of iterators in Python, particularly when using the copy.copy() and copy.deepcopy() functions. I have the following script:
import copy
my_list = ["a",...
-5
votes
1
answer
151
views
calling a class object in an iterative way on python
I made the next class
obj = MyClass()
fds=['a','b','c']
for i in fds:
attribute_name = f"{i}"
setattr(obj, attribute_name, [f"{i}"])
print(obj.i)
I know that obj.i is ...
4
votes
2
answers
229
views
Can the back() iterator of a vector be safely assumed to be the end() iterator after a pop_back()?
My problem is the following :
std::vector<struct pollfd> vec = { ... }; // Actually a member variable on a Server object
for (auto iter = vec.begin(); iter != vec.end(); ) {
if (...
2
votes
1
answer
98
views
How to return an empty **peekable** iterator in Rust?
I have the following Rust function
fn query_list_or_empty<'a, P, R>(
conn: &'a mut SimpleConnection,
sql: &'a str,
params: P,
) -> Peekable<Box<dyn Iterator<Item =...
1
vote
1
answer
138
views
Why does passing a Map.entries() iterator as child to a Collaspsible from shadcn render nothing unless I wrap it with Array.from()?
I’m using shadcn/ui with Radix UI’s Collapsible to make a collapsible filter section.
Wrapper component:
import { ReactNode, useEffect, useState } from "react";
import { Collapsible, ...
1
vote
1
answer
270
views
Is there a Rust way to `continue` a loop inside a `map` closure?
I found this question here but that one doesn't really answer my question due to it having an answer centered around unwrap_or_else.
Here is the code I am trying to use, simplified:
let x = loop {
...
4
votes
2
answers
195
views
Why is `iterator_category` deleted in `std::views::concat::iterator` if it's a pure input iterator?
In the C++26-adopted proposal p2542, i.e. std::views::concat, there is a confusing statement:
The member typedef-name iterator_category is defined if and only if all-forward<Const, Views...> is ...
4
votes
1
answer
165
views
Can't resume using the Iterator helper object
✔ 1. This, with iterator object, works:
let m = n => n * 2;
let it1 = [1, 2, 3].values ();
let [a1] = it1.map (m),
[...b1] = it1.map (m);
console.log (a1 + '', b1 + ''); // '2', '4,6'
✘ 2. ...
0
votes
3
answers
230
views
Confusion about invalidated iterators
If vectors are stored contiguously, as long as they are not made smaller or reallocated, any iterator pointing to an element within it should be valid. The following code would be defined:
#include &...
8
votes
2
answers
288
views
Why do `std::views::adjacent` iterators increment all underlying iterators instead of using a more performant shift?
In C++23, std::views::adjacent<N> provides a sliding window of N elements over a range. Its iterator typically stores N iterators to the underlying range. When implementing this iterator's ...
0
votes
2
answers
106
views
How to write a fold method for an iterator in a language without mutability?
Suppose you had a programming language in which all variables are immutable. Modifying iterables could be accomplished by providing a magic variable that is immutable during an iteration step, but ...
1
vote
1
answer
78
views
C++ Polymorphic Iterators in Abstract Base Class with Custom Child Implementations
I'm working on a C++ project where I have an abstract base class Store that represents a container of Bin objects. Each subclass of Store (e.g., DenseStore, SparseStore) uses a different internal data ...
1
vote
1
answer
83
views
Check if all elements in vector fall within specified range
I have x_min and x_max, both i16 and x_coordinates, which is a Vec<i16>.
Now, I want to check whether every x_coordinate lies between x_min and x_max.
I came up with the following solution, ...
0
votes
1
answer
122
views
Can we traverse stack in FIFO order without custom logic?
My teammate asked if we can traverse stack in FIFO (First In First Out) order. I say stack itself maintain LIFO order in it but we can traverse it in FIFO manner by using another stack or list. Then ...
2
votes
1
answer
218
views
Is performance of std::rotate hampered by the iterator interface?
While standard algorithms should be as optimized as possible based on the iterator category, it seems to me like a lot of performance is left on the table by not being able to consider the underlying ...
2
votes
2
answers
80
views
Is there a way to release and recapture references in closures while iterating?
I have code analogous to:
struct L {
length: usize,
count: usize,
}
impl L {
fn iter(&self, ns: impl Iterator<Item=usize>) -> impl Iterator<Item=usize> {
ns....
2
votes
1
answer
228
views
Which is a better way to move an iterator one step forward: `for x in iterator: break` or `x = next(iterator, None)`?
While working on a learning task involving overlapping n-wise windows from an input iterable - similar to what itertools.pairwise does - I came across code like this:
def f(seq):
it = iter(seq)
...
-3
votes
1
answer
116
views
iterator and iterable classes in python
Why do we return self in the iter method when we define the next method in the iterable and iterator classes?
This topic was taught in the course, but it was hard to understand and I didn't understand ...
-2
votes
1
answer
99
views
Equivalence of two algorithms using backwards and forwards iterators
Given
struct pt{int x,y;};
auto cmpSet = [](pt a, pt b) { return a.x<b.x;};
std::set<pt, decltype(cmpSet)> s(cmpSet);
Are
if(upper==s.begin()) continue;
auto it= std::prev(upper);
while(it!=...
4
votes
2
answers
171
views
Why doesn't range-based for loop match rvalue-reference modifier of this?
#include <vector>
class MyContainer {
public:
std::vector<int> data;
// begin() only defined for rvalues
auto begin() && { return data.begin(); }
auto end() &&...
0
votes
1
answer
110
views
Is there an iterator transform that maps and inserts?
I need to process a vector of items. For each item, I need to apply a transform. For some of the items, I also need to insert a new item. I've looked through the standard Rust iterator transforms ...
-2
votes
2
answers
93
views
Iterate over an object that is not an iterator
I'm not sure why I can iterate over an object that is not an iterator?
>>> import spacy
>>> nlp = spacy.load("en_core_web_sm") ...
2
votes
2
answers
100
views
Creating an iterator over the `OccupiedEntry`s of a `HashSet` in Rust
Edit
I'm realizing that since Entrys own mutable borrows on their parent HashSets, it is impossible for multiple Entrys in a single HashSet to exist simultaneously. Therefore, Entrys will probably not ...
0
votes
2
answers
95
views
Iterating over a reference multiple times over an arbitrary iterator
The following code works:
fn do_it_fun<I>(words: Vec<&str>, inputs: I)
where I: AsRef<[&'static str]>
{
for word in words {
if inputs.as_ref().into_iter()...
0
votes
0
answers
121
views
Write the output of a large iterator to a file
I'm looking to write an iterator Item = u8 to a file. The iterator has a large len so collecting the iterator and then writing the resulting vector isn't very efficient.
I'm thinking of collecting ...
4
votes
2
answers
148
views
C++ function parameter that only accepts iterator to a specific type
I know I can use a template to make a constructor which accepts any type of iterator like this:
struct Thing
{
std::vector<int> integers;
std::list<std::string> strings;
template &...
0
votes
1
answer
87
views
Create mutable iterator over a set of indices?
I'm trying to implement an array where items can occupy multiple slots (details not relevant to question).
I have created a method that allows me to iterate over a range of items:
pub fn get(&self,...
2
votes
2
answers
202
views
Does the standard require `operator->()` to be defined for past-the-end non-contiguous iterators?
Does the standard require that operator->() is defined for non-contiguous past-the-end iterators?
Background:
Regardless of the iterator category, it is allowed for operator*() to exhibit ...
17
votes
2
answers
691
views
Is comparing two spans pointing to the same container well defined?
Is the comparison of begin() and end() iterators of two std::spans that point to the same memory well defined?
#include <span>
#include <cassert>
int main() {
int arr[5]{1,2,3,4,5};
...
0
votes
2
answers
322
views
Is there an idiomatic way to partition a Rust iterator into multiple iterators by Enum variant?
I am struggling to find a clean/idiomatic approach to partition an iterator into a fixed number of sub parts based on Enum variants.
Example
enum State {
A(A),
B(B),
C(C),
}
let states = vec!...
2
votes
3
answers
148
views
How to use output iterators without a container: Set intersection without storage
The C++ reference has this example for printing the intersection of two sets (or sorted containers):
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector&...