首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

std::basic_string::at

reference at( size_type pos );

const_reference at( size_type pos ) const;

返回对指定位置的字符的引用。pos执行边界检查,类型除外std::out_of_range将引发无效访问。

参数

pos

-

position of the character to return

返回值

引用请求的字符。

例外

抛出std::out_of_range如果pos >= size()...

复杂性

常量。

二次

代码语言:javascript
复制
#include <stdexcept>
#include <iostream>
#include <string>
 
int main()
{
    std::string s("message"); // for capacity
 
    s = "abc";
    s.at(2) = 'x'; // ok
    std::cout << s << '\n';
 
    std::cout << "string size = " << s.size() << '\n';
    std::cout << "string capacity = " << s.capacity() << '\n';
 
    try {
        // throw, even if capacity allowed to access element
        s.at(3) = 'x';
    }
    catch (std::out_of_range const& exc) {
        std::cout << exc.what() << '\n';
    }
}

二次

产出:

二次

代码语言:javascript
复制
abx
string size = 3
string capacity = 7
basic_string::at

二次

另见

operator[]

access specified character (public member function)

代码语言:txt
复制
 © cppreference.com

在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。

扫码关注腾讯云开发者

领取腾讯云代金券