std::vector<T,Allocator>::begin, std::vector<T,Allocator>::cbegin_C++中文网
位置:首页 > C++ 参考手册 >容器库 >std::vector > std::vector<T,Allocator>::begin, std::vector<T,Allocator>::cbegin
| iterator begin(); |
(C++11 前) | |
| iterator begin() noexcept; |
(C++11 起) | |
| const_iterator begin() const; |
(C++11 前) | |
| const_iterator begin() const noexcept; |
(C++11 起) | |
| const_iterator cbegin() const noexcept; |
(C++11 起) | |
返回指向 vector 首元素的迭代器。
若 vector 为空,则返回的迭代器将等于 end() 。
参数
(无)
返回值
指向首元素的迭代器。
复杂度
常数。
示例
#include <iostream> #include <vector> #include <string> int main() { std::vector<int> ints {1, 2, 4, 8, 16}; std::vector<std::string> fruits {"orange", "apple", "raspberry"}; std::vector<char> empty; // 求和 vector ints 中的所有整数(若存在),仅打印结果。 int sum = 0; for (auto it = ints.cbegin(); it != ints.cend(); it++) sum += *it; std::cout << "Sum of ints: " << sum << "\n"; // 打印 vector fruits 中的首个水果,而不检查是否有一个。 std::cout << "First fruit: " << *fruits.begin() << "\n"; if (empty.begin() == empty.end()) std::cout << "vector 'empty' is indeed empty.\n"; }
输出:
Sum of ints: 31 First fruit: orange vector 'empty' is indeed empty.