std::string front() 方法
- 自 C++20 起
- 自 C++11 起
// Non const version
constexpr CharT& front();
// Const version
constexpr const CharT& front() const;
// Non const version
CharT& front();
// Const version
const CharT& front() const;
返回对指定索引pos
处元素的引用。
未定义行为
在空字符串上调用 front()
是未定义行为。
参数
(无)
返回值
指向第一个字符的引用。
复杂度
常数 - O(1)。
备注
对于字符串 str
,表达式 str.front()
等价于 *str.begin()
和 str[0]
。
示例
Main.cpp
#include <iostream>
#include <string>
int main()
{
{
std::string s("Exemplary");
char& f = s.front();
f = 'e';
std::cout << s << '\n'; // "exemplary"
}
{
std::string const c("Exemplary");
char const& f = c.front();
std::cout << &f << '\n'; // "Exemplary"
}
}
输出
exemplary
Exemplary