C++ 标准库 - <iterator>

C++ std::begin / std::end 对容器调用成员 begin / end,对内置数组则给出指针区间。写泛型代码时优先用它们,而不是只写 v.begin()。

原型

auto begin(C& c) -> decltype(c.begin());
T* begin(T (&array)[N]);

参数

  • 容器或数组。

返回值

指向首元素的迭代器(或指针),end 指向尾后。

示例

#include <iostream>
#include <iterator>
#include <vector>

int main() {
    std::vector<int> v{1, 2, 3};
    for (auto it = std::begin(v); it != std::end(v); ++it) {
        std::cout << *it << " ";
    }
    std::cout << "\n";
    return 0;
}

输出:

1 2 3 

注意事项

范围 for 在底层就是这一对端点。不要解引用 end。

下一页介绍back_inserter。