Przejdź do głównej zawartości

std::string_view end() method

// Const version only
constexpr iterator end() const noexcept;

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

Returns an iterator

to the element past the end of the view.

If the array is empty, the returned iterator will be equal to begin().

Undefined Behavior

Attempting to dereference a past the end iterator is undefined behaviour

.

Parameters

(none)

Return value

Iterator to the character following the last character.

Complexity

Constant - O(1).

Notes

For a container c, the expression *std::prev(c.end()) is equivalent to c.back().

Difference between end and cend

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

#include <string_view>

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

Example

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

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

auto end = str_view.end();
auto cend = str_view.cend();

std::cout << *std::prev(end) << '\n';
std::cout << *std::prev(cend) << '\n';

std::cout << std::boolalpha << (end == cend) << '\n';
}
Output
d
d
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 end() method

// Const version only
constexpr iterator end() const noexcept;

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

Returns an iterator

to the element past the end of the view.

If the array is empty, the returned iterator will be equal to begin().

Undefined Behavior

Attempting to dereference a past the end iterator is undefined behaviour

.

Parameters

(none)

Return value

Iterator to the character following the last character.

Complexity

Constant - O(1).

Notes

For a container c, the expression *std::prev(c.end()) is equivalent to c.back().

Difference between end and cend

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

#include <string_view>

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

Example

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

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

auto end = str_view.end();
auto cend = str_view.cend();

std::cout << *std::prev(end) << '\n';
std::cout << *std::prev(cend) << '\n';

std::cout << std::boolalpha << (end == cend) << '\n';
}
Output
d
d
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.