◐ Shell
clean mode source ↗

std::vector::begin, std::vector::cbegin — cppreference.com

Материал из cppreference.com

<tbody> </tbody> <tbody class="t-dcl-rev "> </tbody><tbody> </tbody> <tbody class="t-dcl-rev "> </tbody><tbody> </tbody> <tbody class="t-dcl-rev "> </tbody><tbody> </tbody>

iterator begin();

(до C++11)

iterator begin() noexcept;

(начиная с C++11)
(до C++20)

constexpr iterator begin() noexcept;

(начиная с C++20)

const_iterator begin() const;

(до C++11)

const_iterator begin() const noexcept;

(начиная с C++11)
(до C++20)

constexpr const_iterator begin() const noexcept;

(начиная с C++20)

const_iterator cbegin() const noexcept;

(начиная с C++11)
(до C++20)

constexpr const_iterator cbegin() const noexcept;

(начиная с C++20)

Возвращает итератор на первый элемент vector.

Если vector - пуст, возвращаемый итератор будет равен end()

Параметры

(нет)

Возвращаемое значение

Итератор на первый элемент.

Сложность

Константная.

Example

#include <algorithm>
#include <iostream>
#include <numeric>
#include <string>
#include <vector>

int main()
{
    std::vector<int> nums {1, 2, 4, 8, 16};
    std::vector<std::string> fruits {"апельсин", "яблоко", "малина"};
    std::vector<char> empty;

    // Напечатаем vector.
    std::for_each(nums.begin(), nums.end(), [](const int n) { std::cout << n << ' '; });
    std::cout << '\n';

    // Сумма всех чисел в vector nums (если такие есть), печатаем результат.
    std::cout << "Сумма чисел: "
              << std::accumulate(nums.begin(), nums.end(), 0) << '\n';

    // Печатаем первый фрукт в vector fruits, с проверкой если они есть.
    if (!fruits.empty())
        std::cout << "Первый фрукт: " << *fruits.begin() << '\n';

    if (empty.begin() == empty.end())
        std::cout << "vector 'empty' - действительно пуст.\n";
}

Вывод:

1 2 4 8 16
Сумма чисел: 31
Первый фрукт: апельсин
vector 'empty' - действительно пуст.

See also