std::string_view end() method
- od C++17
// 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()
.
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.
- Non const container
- Const container
- end
- cend
#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!
}
#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!
}
- end
- cend
#include <string_view>
int main()
{
const std::string_view str = "Hello";
auto it = str.end(); // Type: std::string_view::const_iterator
*std::prev(it) = 'J'; // ❌ Error!
}
#include <string_view>
int main()
{
const std::string_view str = "Hello";
auto it = str.cend(); // Type: std::string_view::const_iterator
*std::prev(it) = 'J'; // ❌ Error!
}
Example
#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';
}
d
d
true
Hover to see the original license.