名稱空間
變體
操作

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

來自 cppreference.com
< 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> 的公共成員函式) [編輯]