一、begin
begin是STL中一个常用的函数,其作用是返回一个指向容器第一个元素的迭代器。begin函数用法与cbegin大体相同,但返回类型不同,begin返回的是迭代器,而cbegin返回的是const迭代器。
#include <vector>
#include <iostream>
using namespace std;
int main()
{
vector v = {1, 2, 3, 4, 5};
auto it = v.begin();
cout << *it << endl; // 输出1
return 0;
}
在上面的例子中,v.begin()返回vector的第一个元素的迭代器,这个迭代器被保存在变量it中。我们还可以通过it指向的元素得到元素的值。
二、c语言begin用法
在c语言中,没有名为cbegin的函数,但我们可以通过强制类型转换将一个指针转换为const指针。与cbegin类似,我们可以使用该变量来访问数组的元素,同时保证不会修改该变量指向的数据。
#include <stdio.h>
int main()
{
int a[] = {1, 2, 3, 4, 5};
const int* p = (const int*)a;
printf("%d\n", *p); // 输出1
return 0;
}
在上面的例子中,我们将数组a的地址强制转换为一个指向const int的指针p。由于p是const变量,因此无法通过p修改a数组中的值。
三、begin函数
begin函数是C++标准库中定义的函数,可以用于获取指向一个数组或容器中第一个元素的迭代器。
#include <iostream>
#include <array>
using namespace std;
int main()
{
array arr = {1, 2, 3, 4, 5};
auto it = begin(arr);
cout << *it << endl; // 输出1
return 0;
}
在上面的例子中,begin函数返回数组arr的第一个元素的迭代器,该迭代器被保存在变量it中。我们还可以通过it指向的元素得到元素的值。
四、map容器begin函数
map容器是C++标准库中的一种关联式容器,我们可以使用map的begin函数返回指向map容器的第一个元素的迭代器。
#include <iostream>
#include <map>
using namespace std;
int main()
{
map<string, int> m;
m["apple"] = 10;
m["orange"] = 20;
auto it = m.begin();
cout << it->first << " " << it->second << endl; // 输出"apple 10"
return 0;
}
在上面的例子中,我们使用map容器存储了一些水果的数量。map的begin函数返回一个迭代器,该迭代器指向map容器中第一个元素。
总结
通过对cbegin的介绍与实例解析,我们可以了解到cbegin函数是STL中用于返回指向容器第一个元素的const迭代器的函数。除此之外,我们还介绍了begin函数,map容器begin函数,以及c语言中如何使用指针来模拟cbegin函数的功能。
原创文章,作者:小蓝,如若转载,请注明出处:https://www.506064.com/n/180243.html
微信扫一扫
支付宝扫一扫