命名空间
变体
操作

std::basic_string<CharT,Traits,Allocator>::front

来自 cppreference.cn
< cpp‎ | string‎ | basic_string
 
 
 
std::basic_string
 
CharT& front();
(1) (C++20 起为 constexpr)
const CharT& front() const;
(2) (C++20 起为 constexpr)

返回字符串中第一个字符的引用。如果 empty()true,则行为未定义。

目录

[编辑] 参数

(无)

[编辑] 返回值

返回第一个字符的引用,等价于 operator[](0)

[编辑] 复杂度

常数时间。

[编辑] 注意

在 libstdc++ 中,`front()` 在 C++98 模式下不可用

[编辑] 示例

#include <iostream>
#include <string>
 
int main()
{
    std::string s("Exemplary");
    char& f1 = s.front();
    f1 = 'e';
    std::cout << s << '\n'; // "exemplary"
 
    std::string const c("Exemplary");
    char const& f2 = c.front();
    std::cout << &f2 << '\n'; // "Exemplary"
}

输出

exemplary
Exemplary

[编辑] 缺陷报告

下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。

缺陷报告 应用于 发布时的行为 正确的行为
LWG 534 C++98 std::basic_string 没有成员函数 front() 已添加

[编辑] 参阅

(DR*)
访问最后一个字符
(公共成员函数) [编辑]
访问第一个字符
(std::basic_string_view<CharT,Traits> 的公共成员函数) [编辑]