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,那麼行為未定義。

(C++26 前)

如果 empty()true,那麼:

  • 如果實現是硬化實現,那麼就會發生契約違背。並且契約違背處理函數在「觀察」求值語義下返回時行為未定義。
  • 如果實現不是硬化實現,那麼行為未定義。
(C++26 起)

目錄

[編輯] 返回值

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 534C++98std::string 沒有成員函數 front()已添加

[編輯] 參閱

(DR*)
訪問最後的字符
(公開成員函數) [編輯]
訪問首個字符
(std::basic_string_view<CharT,Traits> 的公開成員函數) [編輯]