本文主要介绍C++编程语言的STL(Standard Template Library)中begin和end函数的相关知识,同时通过示例代码介绍这两个函数的常见用法。
1 概述
begin函数用于返回给定范围内的起始点,具体分为以下情况:
- c.begin()形式:返回指向容器首元素的iterator;
- begin(array)或begin(c)形式:返回数组的头指针。
end函数用于返回给定范围内的终止点(即,在最后一个元素之后的元素),具体分为以下情况:
- c.end()形式:返回指向紧挨尾元素的元素的iterator;
- end(array)或end(c)形式:返回紧挨数组尾指针的指针。
说明:对于end函数来说,给定范围的“终止点”并不包含在给定范围内,而是紧挨着范围内最后一个可用元素的元素。
对于begin/end函数来说,参数描述如下:
- c: 包括begin成员函数/end成员函数的容器;
- array: 任意类型的数组
通过下图可以更直观地理解begin和end函数的返回值:
2 示例代码
下面给出一个使用begin和end函数的示例代码:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> c{1, 2, 3, 4, 5};
cout << "c.begin() output is: \n";
for (auto it = c.begin(); it != c.end(); ++it) {
cout << *it << ' ';
}
cout << "\nbegin(c) output is: \n";
cout << *begin(c);
cout << "\nend(c) output is: \n";
cout << *end(c) << endl;
return 0;
}
说明:
- *end(c)的结果为0,说明该函数返回的内容不在vector之内。