for_each that gives two or n adjacent elements
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.
Introduction
The standard std::for_each operates on one element at a time, but many algorithms need to process pairs or windows of adjacent elements — computing differences, detecting changes, or applying sliding-window operations. C++23 added std::views::adjacent and std::views::slide for this purpose. In C++17 and earlier, use std::adjacent_find with a custom predicate, manual iterator arithmetic, or a custom for_each_adjacent function. For Python and JavaScript, the equivalent patterns use zip, itertools.pairwise, or Array.reduce.
C++23: views::adjacent and views::slide
std::views::adjacent<N> produces a view of tuples containing N consecutive elements from the range. It is a compile-time fixed-size sliding window.
C++23: views::slide (Runtime Window Size)
std::views::slide(n) produces subranges of size n, where n can be determined at runtime. Each subrange is a view into the original container.
C++17: Custom for_each_adjacent
This is the pre-C++23 solution. The template works with any forward iterator and any binary function.
C++17: N-Element Sliding Window
Using std::adjacent_find as a Workaround
This is a hack — std::adjacent_find is designed to find the first adjacent pair matching a predicate, but returning false forces it to visit every pair. Use the custom function template for production code.
Python: itertools.pairwise (3.10+)
JavaScript: Adjacent Element Patterns
Common Pitfalls
- Off-by-one with window size: A container of N elements has N-1 adjacent pairs, N-2 triples, and so on. Forgetting this leads to out-of-bounds access. Always check that the container size is at least the window size before iterating.
- Iterator invalidation: If the callback modifies the container (inserting or erasing elements), iterators become invalid. Never modify the container during a sliding-window traversal. Copy data if mutation is needed.
- Using
std::adjacent_findfor side effects: The standard does not guaranteeadjacent_findprocesses all pairs if it finds a match. Thereturn falsehack works for visiting all pairs but is fragile and unclear. Use a custom function instead. - Performance with large windows: A naive sliding window copies elements for each position. For large windows, use a deque-based approach that adds one element and removes one per step, achieving O(1) per window instead of O(window_size).
views::adjacentrequires random access: In C++23,std::views::adjacent<N>works best with random-access ranges. For forward-only ranges (likestd::forward_list), it may not compile or may have degraded performance. Check the range concept requirements.
Summary
- C++23 provides
std::views::adjacent<N>(compile-time) andstd::views::slide(n)(runtime) for sliding windows - In C++17, write a custom
for_each_adjacenttemplate using iterator pairs std::adjacent_findcan visit all pairs as a workaround but is not designed for this purpose- Python 3.10+ has
itertools.pairwise()for adjacent pairs; use a generator for arbitrary window sizes - JavaScript uses index-based iteration or
Array.slicefor sliding windows - Always check that the container has enough elements for the requested window size
Related reading
- For given two integers A and B, find a pair of numbers X and Y such that A XY and B X xor Y
- For parallel algorithm with N threads, can performance gain be more than N?
- Ford Fulkerson from Cormen et al
- Formally verifying the correctness of an algorithm
- Four color theorem Java implementation of U.S. map
- Free Face Detection Algorithm for Video
- From a string without length constraint, How to generate multiple random strings with length constraint?
- From list of integers, get number closest to a given value

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.