iterator_count / iterator_apply

iterator_count(Traversable|array $iterator): int / iterator_apply(Traversable $iterator, callable $callback, ?array $args = null): int

迭代器辅助二件套:iterator_count 数元素但会走完(消耗)迭代器(位置不保留);iterator_apply 对每元素调用回调(回调须返回 true 才继续),返回迭代次数。

C C23

C23
#include <stdio.h>
#include <string.h>

/* 最小一次性游标:走过末尾之后就永远耗尽 */
typedef struct {
    const char *s;
    size_t pos, len;
} Cursor;

static int cursor_next_word(Cursor *c) {
    while (c->pos < c->len && c->s[c->pos] == ' ') c->pos++; /* 跳过空格 */
    if (c->pos >= c->len) return 0; /* 耗尽:一次性 */
    while (c->pos < c->len && c->s[c->pos] != ' ') c->pos++;
    return 1;
}

int main(void) {
    Cursor c = {0}; /* 零初始化缓冲 */
    c.s = "apple banana cherry";
    c.len = 19;
    int n = 0;
    while (cursor_next_word(&c)) n++; /* 计数即消耗游标 */
    printf("count=%d; second pass=", n);
    int again = 0;
    while (cursor_next_word(&c)) again++; /* 游标已耗尽:仍为零 */
    printf("%d\n", again);
    return 0;
}
输出
count=3; second pass=0

C++ C++26

C++26
#include <iostream>
#include <iterator>
#include <sstream>
#include <vector>

int main() {
    // std::istream_iterator 是单遍输入迭代器:std::distance 走一遍就消耗掉
    std::istringstream in("apple banana cherry");
    std::istream_iterator<std::string> first(in), last;
    std::cout << "count=" << std::distance(first, last) << '\n';
    // 输入迭代器是单遍的:再走一遍要拿全新的迭代器
    std::istringstream in2("apple banana cherry");
    std::cout << "fresh pass="
              << std::distance(std::istream_iterator<std::string>(in2),
                               std::istream_iterator<std::string>()) << '\n';
    std::vector<std::string> v{"apple", "banana", "cherry"};
    std::cout << "random-access count=" << std::distance(v.begin(), v.end()) << '\n';
    return 0;
}
输出
count=3
fresh pass=3
random-access count=3

C# v11.0.100

v11.0.100
using System;
using System.Collections.Generic;
using System.Linq;

IEnumerable<string> Seq()
{
    yield return "apple";
    yield return "banana";
    yield return "cherry";
}

// Count() 会枚举整个序列;IEnumerable 每次重新枚举都从新游标开始
var first = Seq();
Console.WriteLine($"enumerated={first.Count()}");
var second = Seq();
Console.WriteLine($"re-enumerated={second.Count()}");
输出
enumerated=3
re-enumerated=3

Go v1.27.4

v1.27.4
package main

import (
	"bufio"
	"fmt"
	"strings"
)

func main() {
	// bufio.Scanner 是一次性迭代器:计数即消耗
	sc := bufio.NewScanner(strings.NewReader("apple\nbanana\ncherry"))
	n := 0
	for sc.Scan() {
		n++
	}
	fmt.Println("count=", n, "; scan again=", sc.Scan())
}
输出
count= 3 ; scan again= false

Java v27.0.1

v27.0.1
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;

public class Main {
    public static void main(String[] args) {
        List<String> data = Arrays.asList("apple", "banana", "cherry");
        Stream<String> s1 = data.stream();
        System.out.println("stream count=" + s1.count()); // count 即消耗流
        Stream<String> s2 = data.stream(); // 流是一次性的:再拿一条新的
        System.out.println("second stream count=" + s2.count());
        System.out.println("collection size=" + data.size());
    }
}
输出
stream count=3
second stream count=3
collection size=3

JavaScript v26.13.1

v26.13.1
// 生成器是一次性迭代器:展开即消耗,之后就耗尽
function* items() {
  yield "apple";
  yield "banana";
  yield "cherry";
}
const it = items();
const n = [...it].length;
console.log(`count=${n}; second pass=${[...it].length}`);
输出
count=3; second pass=0

PHP v8.6.0

v8.6.0
// iterator_count 数元素但会走完(消耗)前向迭代器:
// 位置不保留(迭代器恰好走一遍)。
$it = new ArrayIterator(['pancakes', 'egg', 'milk', 'flour']);
echo 'count=', iterator_count($it), '; current after=', var_export($it->current(), true), "\n";
// iterator_apply 在回调返回 true 期间逐元素调用,
// 返回实际迭代的次数。
$it2 = new ArrayIterator(['apple', 'banana', 'cherry']);
$n = iterator_apply($it2, function (Iterator $it) {
    echo strtoupper($it->current()), "\n";
    return true; // 必须返回 true 才继续迭代
}, [$it2]);
echo 'applied=', $n;
输出
count=4; current after=NULL
APPLE
BANANA
CHERRY
applied=3

Python v3.15.2

v3.15.2
# len(list(it)) 会把生成器物化成列表:生成器是一次性迭代器
def items():
    yield "apple"
    yield "banana"
    yield "cherry"

it = items()
print("count=", len(list(it)), "; second pass=", len(list(it)))
输出
count= 3 ; second pass= 0

Rust v1.99.1

v1.99.1
// Iterator::count() 会消耗迭代器:一次性适配器用过即耗尽
fn main() {
    let data = vec!["apple", "banana", "cherry"];
    let it = data.iter().map(|s| s.to_uppercase());
    let n = it.count();
    println!("count={n}; reusable=no");
}
输出
count=3; reusable=no

TypeScript v26.13.1

v26.13.1
// 生成器是一次性迭代器:展开即消耗,之后就耗尽
function* items(): Generator<string> {
  yield "apple";
  yield "banana";
  yield "cherry";
}
const it = items();
const n: number = [...it].length;
console.log(`count=${n}; second pass=${[...it].length}`);
输出
count=3; second pass=0

语言差异说明

PHP:iterator_count 数元素前会把迭代器走完——手册明言不保证保留当前位置(示例里 count 之后 current() 已是 NULL),这 teachable moment 与 iterator_to_array(见该条目)同源:迭代器只能走一次,数完/取完即耗尽,NoRewindIterator 更是不可回退。8.2 起参数放宽为 Traversable|array(直接给数组也行)。iterator_apply 是「回调式遍历」:回调必须返回 true 才继续(返回假值即停),返回值为实际迭代次数——相当于 array_walk 的迭代器版;注意回调参数通过第三参数显式传入(不会自动收到当前元素),要用 current()/key() 自己取。

C:没有迭代器协议,示例手写一个 one-shot 游标结构(pos 走过 len 即永远耗尽)演示「计数即消耗」语义;零初始化用 Cursor c = {0}。

C++:std::istream_iterator 是输入迭代器(单遍)——std::distance 走一遍即消耗,再走要拿全新的流;std::distance 对随机访问迭代器(vector)是 O(1) 减法,对输入迭代器是 O(n) 走一遍,同一名两语义。

C#:Count()(LINQ)枚举整个序列计数;与 PHP 不同,IEnumerable 契约上可重复枚举(每次 GetEnumerator 都是全新游标),真正的一次性场景是直接枚举 StreamReader/网络流这类。

Go:bufio.Scanner(示例)是一次性迭代器——Scan 到底之后 Scan() 恒为 false;没有泛型迭代器协议(1.23 起有 range-over-func 迭代器,同样单遍)。

Java:Stream.count() 是规约终端操作——数完流即关闭;再数要 data.stream() 拿新流(示例的 s2);底层集合的 size() 才是 O(1) 且可重复——与 PHP 的 ArrayIterator(走完后 current 为 NULL)对照鲜明。

JavaScript:生成器是一次性迭代器——[...it] 展开即消耗,第二次展开得 0;想要可重复计数就先物化成数组(与 Python 的 list(it) 同一手法)。

Python:len(list(it))(示例)是惯用法——物化成列表再数;生成器耗尽后 list(it) 得空表;纯计数可用 sum(1 for _ in it) 免物化,但同样消耗迭代器。

Rust:Iterator::count() 消耗 self——用完即 moved,再调用编译不过(所有权机制把「只能走一次」做成编译期约束,四门语言里唯一);.len() 只属于集合自身,与迭代器消耗无关。

TypeScript:同 JavaScript;类型上 Generator<T> 一次性语义与运行时一致,展开消耗后 length 恒 0。

教学锚点:「计数/遍历即消耗」是流式数据结构的普适契约——PHP iterator_count、Java Stream.count、Rust Iterator::count、Python 生成器、JS 生成器全部如此;例外是「容器类」(数组/集合/List),它们的 size/len/count 可无限重复——区分「迭代器视图」与「容器本体」是本条目的核心。