std::deque begin()/cbegin() 方法
- 自 C++11 起
- 直到 C++11
// Non const version
iterator begin() noexcept;
// Const version
const_iterator begin() const noexcept;
const_iterator cbegin() const noexcept;
// Non const version
iterator begin();
// Const version
const_iterator begin() const;
返回指向数组末尾之后元素的迭代器。
指向 deque 的第一个元素。如果 deque 为空,返回的迭代器将等于
end()
。
参数
(无)
返回值
指向第一个元素的迭代器。
复杂度
常数 - O(1)。
begin 和 cbegin 的区别
对于 const 容器 c
,begin 和 cbegin 是相同的 - c.begin() == c.cbegin()
对于非常量类型c
的容器,它们返回不同的迭代器
- 非常量容器
- 常量容器
- begin
- cbegin
#include <deque>
#include <string>
int main()
{
std::deque<int> deque = { 1, 2, 3 };
auto it = deque.begin(); // Type: std::deque<int>::iterator
*it = 5; // ✔ Ok
}
#include <deque>
#include <string>
int main()
{
std::deque<int> deque = { 1, 2, 3 };
auto it = deque.cbegin(); // Type: std::deque<int>::const_iterator
*it = 5; // ❌ Error!
}
- begin
- cbegin
#include <deque>
#include <string>
int main()
{
const std::deque<int> deque = { 1, 2, 3 };
auto it = deque.begin(); // Type: std::deque<int>::const_iterator
*it = 5; // ❌ Error!
}
#include <deque>
#include <string>
int main()
{
const std::deque<int> deque = { 1, 2, 3 };
auto it = deque.cbegin(); // Type: std::deque<int>::const_iterator
*it = 5; // ❌ Error!
}
示例
Main.cpp
#include <algorithm>
#include <iostream>
#include <numeric>
#include <string>
#include <deque>
int main()
{
std::deque<int> nums {1, 2, 4, 8, 16};
std::deque<std::string> fruits {"orange", "apple", "raspberry"};
std::deque<char> empty;
// Print deque.
std::for_each(nums.begin(), nums.end(), [](const int n) { std::cout << n << ' '; });
std::cout << '\n';
// Sums all integers in the deque nums (if any), printing only the result.
std::cout << "Sum of nums: "
<< std::accumulate(nums.begin(), nums.end(), 0) << '\n';
// Prints the first fruit in the deque fruits, checking if there is any.
if (!fruits.empty())
std::cout << "First fruit: " << *fruits.begin() << '\n';
if (empty.begin() == empty.end())
std::cout << "deque 'empty' is indeed empty.\n";
}
可能的输出
1 2 4 8 16
Sum of nums: 31
First fruit: orange
deque 'empty' is indeed empty.