STL begin和end函数

STL begin和end函数教程

无论是 序列式容器 还是 关联式容器(包括哈希容器),不仅模板类内部提供有 begin() 和 end() 成员方法,C++ STL 标准库中还提供有同名且具有相同功能的 begin() 和 end() 函数。

begin() 和 end() 是以函数模板的形式定义的,但它们的模板并没有位于某一个头文件中,而是很多头文件中都有它们的定义。

不仅如此,begin() 和 end() 都位于 std 命名空间中。因此,在使用这 2 个函数之前,程序中应引入容纳它们函数模板的头文件以及 std 命名空间。在实际的使用场景中,begin() 和 end() 函数往往会一起使用的。

STL begin和end详解

说明

当将某个具体容器作为参数分别传给 begin() 和 end() 函数时,其中 begin() 底层会执行 begin() 语句,而 end() 底层会执行 end() 语句,它们最终会将得到的迭代器作为函数的返回值反馈回来。

当作用对象为容器时,end() 和 begin() 函数的语法格式是完全一样的。

语法

//非 const 修改的容器作为参数,begin() 函数返回的为非 const 类型的迭代器 template <class Container> auto begin (Container& cont) //传入 const 修饰的容器,begin() 函数返回的为 const 类型的迭代器 template <class Container> auto begin (const Container& cont)

参数

参数 描述
cont 表示指定的容器。

技术细节

其中,cont 表示指定的容器;同时,函数会返回一个有特定指向的迭代器,且此迭代器的类型也取决于 cont 容器。

以上 2 种格式的区别仅在与传入的容器是否有 const 修饰,即如果有,则通过该函数获得的迭代器也有 const 修饰(不能用于修改容器中存储的数据);反之就没有。

补充

除了可以将指定容器作为参数传给 begin() 和 end() 之外,还可以指定数组作为参数传给它们。将指定数组传给 begin() 函数,其会返回一个指向该数组首个元素的指针;将指定数组传给 end() 函数,其会返回一个指向数组中最后一个元素之后位置的指针。

同样,数组作为参数时,end() 函数的语法格式和 begin() 函数也完全一样

案例

begin()和end()参数为容器

begin() 和 end() 参数为容器

#include <iostream> #include <vector> using namespace std; int main() { cout << "嗨客网(www.haicoder.net)\n" << endl; std::vector<int> myvector{1024, 200, 303, 404, 500}; for (auto it = begin(myvector); it != end(myvector); ++it) { cout << *it << ' '; } cout << endl; return 0; }

我们在 Linux 下使用 g++ 进行编译,具体命令如下:

g++ begin.cpp

编译后,我们直接运行生成的二进制文件 a.out,如下图所示:

18_STL begin和end函数.png

上述代码中的 begin(myvector) 等同于执行 myvector.begin(),而 end(myvector) 也等同于执行 myvector.end()

begin()和end()参数为数组

begin() 和 end() 参数为数组

#include <iostream> #include <vector> using namespace std; int main() { cout << "嗨客网(www.haicoder.net)\n" << endl; int arr[] = {1024, 200, 303, 404, 500}; for (auto it = begin(arr); it != end(arr); ++it) { cout << *it << ' '; } cout << endl; return 0; }

我们在 Linux 下使用 g++ 进行编译,具体命令如下:

g++ begin.cpp

编译后,我们直接运行生成的二进制文件 a.out,如下图所示:

19_STL begin和end函数.png

我们使用了 begin 和 end 访问了数组的元素。

STL begin和end函数总结

无论是序列式容器还是关联式容器(包括哈希容器),不仅模板类内部提供有 begin() 和 end() 成员方法,C++ STL 标准库中还提供有同名且具有相同功能的 begin() 和 end() 函数。