用指针访问std ::字符串中的元素

Accessing elements in a std::string with pointers

本文关键字:元素 字符串 访问 std 指针      更新时间:2023-10-16

如何使用指针访问std :: string中的单个元素?如果没有类型铸造到const char *?

#include <iostream>
#include <string>
using namespace std;
int main() {
    // I'm trying to do this...
    string str = "This is a string";
    cout << str[2] << endl;
    // ...but by doing this instead
    string *p_str = &str;
    cout << /* access 3rd element of str with p_str */ << endl;
    return 0;
}

有两种方法:

  1. 明确调用operator[]函数:

    std::cout << p_str->operator[](2) << 'n';
    

    或使用at功能

    std::cout << p_str->at(2) << 'n';
    

    这两个都是几乎等效的。

  2. 或取消指针获取对象,并使用正常索引:

    std::cout << (*p_str)[2] << 'n';
    

无论哪种方式,您都需要取消指针。通过"箭头"操作员->或使用直接取消运算符*无关紧要。