15,025 questions
3
votes
2
answers
273
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
166
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
135
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
94
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
181
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
117
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 ...
2
votes
1
answer
108
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
127
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
37
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 ...
0
votes
0
answers
59
views
Dereference iterator and then iterate over dereferenced value [duplicate]
I have a piece of text with delimiters in it. I need to extract words from it and convert them to lower case. My approach is to use regular expressions to split the text and use transform to convert ...
1
vote
1
answer
80
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
143
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
220
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
88
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
130
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
159
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
183
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
156
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
213
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
264
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
84
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
69
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
79
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
111
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
196
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 ...
0
votes
0
answers
73
views
A rust iterator that must outlive it's references [duplicate]
Context
I'm trying to write a data block with interior mutability, that allows simultaneous access to disjoint areas of memory from the same owner. To do this I have a reservation table that checks if ...
2
votes
2
answers
76
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
189
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
109
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
97
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
154
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
103
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
92
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
96
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
62
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
101
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
135
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
60
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
188
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
658
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
193
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
141
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&...
4
votes
1
answer
103
views
Java iterator of regex matches from large source
The basic problem is that I need to output all matches of a regex within a file, but there's a few properties that make a solution tricky:
The file could be very large, so the whole file cannot be ...
6
votes
1
answer
204
views
What operations are permitted on an invalidated iterator?
There is a footnote in the [iterator.requirements] section of the C++ standard which states the following:
The effect of dereferencing an iterator that has been invalidated is undefined.
This ...
-2
votes
1
answer
83
views
Java Iterator Views
I frequently would like to iterate over a view of some underlying data structure, e.g. a backwards iteration or only a slice of a list. The Java standard library has some support for multiple iterator ...
6
votes
2
answers
88
views
Why is &Range<T> not an iterator, but &mut Range<T> is?
Demo code using version rustc 1.86.0 (05f9846f8 2025-03-31)
fn main() {
let mut source = 1..3;
test(&mut source); // This is good. which means &mut Range<T> is Iterator.
...
1
vote
1
answer
153
views
Can `std::unordered_map::iterator` be implemented without reference to underlying map?
A while back I ported some of the C++ stdlib containers to environment where stdlib was not available. While iterators for contiguous and node-based containers were easy, I was stumped how to ...
3
votes
1
answer
151
views
Inconsistent output with std::any_of
I have two version of the same function using std::any_of and std::find_if for checking whether an int exist in a vector (returned from g.getEdges()).
However when I repeatedly run the std::any_of the ...
2
votes
1
answer
102
views
Why is STL common_iterator's `operator*()` method not always const qualified?
In libstdc++ there is the following code:
class common_iterator
{
...
[[nodiscard]]
constexpr decltype(auto)
operator*()
{
__glibcxx_assert(_M_index == 0);
return *...
3
votes
1
answer
99
views
Is it safe to access elements outside subrange but inside parent range?
Let's say I have an std::vector<int> arr of 5 elements { 1, 2, 3, 4, 5 }.
Is it safe to get a subrange from it like sub = std::span{ arr.begin() + 2, arr.end() } and dereference element at -1 ...