Przejdź do głównej zawartości

std::string_view begin()/cbegin() method

// Const version only
constexpr const_iterator begin() const noexcept;

// Const version only
constexpr const_iterator cbegin() const noexcept;

Returns an iterator

to the first element of the view.

If the view is empty, the returned iterator will be equal to end().

Parameters

(none)

Return value

Iterator to the first character.

Complexity

Constant - O(1).

Notes

For a container c, the expression *c.begin() is equivalent to c.front().

Difference between begin and cbegin

Unlike for other containers, like std::string or std::vector, begin and cbegin both return the same iterator.

#include <string_view>

int main()
{
std::string_view str = "Hello";
auto it = str.cbegin(); // Type: std::string_view::const_iterator
*it = 'J'; // ❌ Error!
}

Example

Main.cpp
#include <iostream>
#include <string_view>
#include <type_traits>

int main()
{
std::string_view str_view("abcd");

auto begin = str_view.begin();
auto cbegin = str_view.cbegin();

std::cout << *begin << '\n';
std::cout << *cbegin << '\n';

std::cout << std::boolalpha << (begin == cbegin) << '\n';
std::cout << std::boolalpha << (*begin == *cbegin) << '\n';

static_assert(std::is_same<decltype(begin), decltype(cbegin)>{});
}
Output
a
a
true
true
This article originates from this CppReference page. It was likely altered for improvements or editors' preference. Click "Edit this page" to see all changes made to this document.
Hover to see the original license.

std::string_view begin()/cbegin() method

// Const version only
constexpr const_iterator begin() const noexcept;

// Const version only
constexpr const_iterator cbegin() const noexcept;

Returns an iterator

to the first element of the view.

If the view is empty, the returned iterator will be equal to end().

Parameters

(none)

Return value

Iterator to the first character.

Complexity

Constant - O(1).

Notes

For a container c, the expression *c.begin() is equivalent to c.front().

Difference between begin and cbegin

Unlike for other containers, like std::string or std::vector, begin and cbegin both return the same iterator.

#include <string_view>

int main()
{
std::string_view str = "Hello";
auto it = str.cbegin(); // Type: std::string_view::const_iterator
*it = 'J'; // ❌ Error!
}

Example

Main.cpp
#include <iostream>
#include <string_view>
#include <type_traits>

int main()
{
std::string_view str_view("abcd");

auto begin = str_view.begin();
auto cbegin = str_view.cbegin();

std::cout << *begin << '\n';
std::cout << *cbegin << '\n';

std::cout << std::boolalpha << (begin == cbegin) << '\n';
std::cout << std::boolalpha << (*begin == *cbegin) << '\n';

static_assert(std::is_same<decltype(begin), decltype(cbegin)>{});
}
Output
a
a
true
true
This article originates from this CppReference page. It was likely altered for improvements or editors' preference. Click "Edit this page" to see all changes made to this document.
Hover to see the original license.