← All lints

manual_pair_loop

L0543Idiomswarn

C++ pair loop

for i ..: for j in i + 1..n: xs.pairs() walks each pair once

Flagged
let n: 1..=2000 = read()
let a: [0..n]Int = read()
var c = 0
for i in 0..n:
    for j in i + 1..n:
        if a[i] + a[j] == 0:
            c += 1
print(c)
Write instead
let n: 1..=2000 = read()
let a: [0..n]Int = read()
print(a.pairs().count(p => p.0 + p.1 == 0))

Why

C++ walks every unordered pair with two loops, the inner one starting at i + 1. pairs() from std.seq yields each pair (x, y) with x before y once, so for (x, y) in a.pairs() says it without index arithmetic; (0..n).pairs() gives the index pairs when the body needs positions. There is no automatic fix, because the body has to change from a[i] and a[j] to the pair's names.

The practice it serves

A hand-written pattern the language or the standard library already says in one step.

Not flagged

A near miss: close to the pattern, but not it.

Near miss
let n: 1..=2000 = read()
let a: [0..n]Int = read()
var c = 0
for i in 0..n:
    for j in i..n:
        if a[i] + a[j] == 0:
            c += 1
print(c)

Turn it off

For one block, wrap it in with lint(manual_pair_loop: allow):. For a project, add manual_pair_loop = "allow" under [lints] in cp.toml.

Generated from spec/lints/manual_pair_loop, the same record the linter is built from.