Transpose A Grid With Nested Iterators
Build the transpose of a grid with nested iterators: one value per row per output column, with the original grid only ever borrowed.
Code
fn transpose(grid: &[Vec<i32>]) -> Vec<Vec<i32>> {
if grid.is_empty() {
return Vec::new();
}
let cols = grid[0].len();
// nested iterators:外层枚举每一列,内层借每一行取一个值,collect 成新行
(0..cols)
.map(|c| grid.iter().map(|row| row[c]).collect())
.collect()
}
fn main() {
let grid = vec![vec![1, 2, 3], vec![4, 5, 6]];
let rotated = transpose(&grid);
println!("transpose: {rotated:?}");
// 内层只用 &row 借用:grid 之后照常可用
let doubled: Vec<Vec<i32>> = grid
.iter()
.map(|row| row.iter().map(|v| v * 2).collect())
.collect();
println!("doubled: {doubled:?}");
println!("grid intact: {:?}", grid[1][2]);
}How it works
Transpose A Grid With Nested Iterators comes down to the functions transpose and main.
Using it
The primary signature is fn transpose(grid: &[Vec<i32>]) -> Vec<Vec<i32>>
The demo output is labeled (transpose:, doubled:, grid intact:), so every printed line maps back to its originating operation.
Treat main as the orchestrator calling transpose in a fixed order.
Key statements
.map(|c| grid.iter().map(|row| row[c]).collect())
.collect()
}
.map(|row| row.iter().map(|v| v * 2).collect())
.collect();
return Vec::new();
Interactive Tools for This Topic
CSS Grid PlaygroundExperiment with CSS grid layout properties interactively. Define columns, rows, gaps, and areas while watching the grid template update in a live visual preview.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- What does Transpose A Grid With Nested Iterators print when run?
- Invoke the file as-is — the `transpose:`, `doubled:`, `grid intact:` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.