一、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/zh-hant/n/180243.html