deque中的cbegin()方法是C++ STL中的函数,该函数返回指向容器第一个元素的迭代器。
用法:
deque_name.cbegin()
返回值:返回一个常量迭代器,该迭代器指向双端队列的第一个元素。这意味着,迭代器可用于遍历队列,但不能修改队列。也就是说,如果使用常量迭代器进行调用,则诸如插入,擦除之类的函数将引发错误。
当您不希望代码的任何部分修改双端队列的内容时,应使用常量迭代器。
以下程序说明了该功能。
示例1:
#include
#include
using namespace std;
int main()
{
// Create a deque
deque dq = { 2, 5, 7, 8, 6 };
// Print the first element of deque
// using cbegin() method
cout << "First element of the deque is: ";
// Get the iterator pointing to the first element
// And dereference it
cout << *dq.cbegin();
}
输出:
First element of the deque is: 2
示例2:
#include
#include
using namespace std;
int main()
{
// Create a deque
deque dq = { 1, 5, 2, 4, 7 };
// Insert an element at the front
dq.push_front(45);
// Insert an element at the back
dq.push_back(56);
// Print the first element of deque
// using cbegin() method
cout << "First element of the deque is: ";
// Get the iterator pointing to the first element
// And dereference it
cout << *dq.cbegin();
}
输出:
First element of the deque is: 45