std::vector<T,Allocator>::begin、<std::vector>T,Allocator::
cbegin
iterator begin();
|
(C++17) | (1) (noexcept 自 C++11) |
const_iterator begin() const;
|
(constexpr 自 C++20) | (2) (noexcept 自 C++11) |
const_iterator cbegin() const noexcept;
|
(constexpr 自 C++20) | (3) (自 C++11) |
(constexpr 自 C++20)vector返回指向
首元素的迭代器。
vector若 为空,则返回的迭代器将等于 end()
返回值
指向第一个元素的迭代器。
复杂度
常量。
注释
libc++ 向后移植
cbegin()
至 C++98 模式。
示例
运行此代码
#include <algorithm>
#include <cassert>
#include <iostream>
#include <numeric>
#include <string>
#include <vector>
int main()
{
std::vector<int> nums{1, 2, 4, 8, 16};
std::vector<std::string> fruits{"orange", "apple", "raspberry"};
std::vector<char> empty;
// Print vector nums.
std::for_each(nums.cbegin(), nums.cend(),
[](const int n) { std::cout << n << ' '; });
std::cout << '\n';
// Sum all integers in the vector nums, printing only the result.
std::cout << "Sum of nums: "
<< std::accumulate(nums.cbegin(), nums.cend(), 0) << '\n';
// Print the first fruit in the vector fruits, checking if there is any.
if (!fruits.empty())
std::cout << "First fruit: " << *fruits.cbegin() << '\n';
if (empty.cbegin() == empty.cend())
std::cout << "vector ‘empty’ is indeed empty.\n";
// Modify the first element in nums.
*nums.begin() = 32;
assert(*nums.cbegin() == 32);
}
输出:
1 2 4 8 16
Sum of nums: 31
First fruit: orange
vector ‘empty’ is indeed empty.
参见
|
(C++11)
|
返回指向末尾的迭代器
(公开成员函数) |
|
(C++11)
(C++14)
|
返回指向容器或数组起始位置的迭代器
(函数模板) |