首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >std::string []运算符与at()的区别

std::string []运算符与at()的区别
EN

Stack Overflow用户
提问于 2018-06-05 03:41:46
回答 1查看 158关注 0票数 -6

在经历了几年的C#、Javascript、web开发等之后,我重新访问了C++。

有一个线程解释说,它们之间的主要区别是at()方法执行边界检查,并在提供的索引超出边界时抛出异常。

What is the difference between string::at and string::operator[]?

然而,这似乎不能证明我正在经历的以下行为是合理的,也许有人可以帮助我?

代码语言:javascript
复制
#include <iostream>
#include <string>

using namespace std;

void remodel(string & str){
    string * ps = new string(str);

    ps->at(0) = 'n';
    cout<<*ps<<endl;
    delete ps;
}

int main(){
    string str = "Hello world";
    remodel(str);
    cin.get();
    return 0;
}

输出

代码语言:javascript
复制
nello world

在上面的代码中,我使用at()方法更改了字符串的第一个字符,并且能够成功地完成此操作。打印字符串可以确认这一点。

使用[]运算符时会发生一些不同的情况:

代码语言:javascript
复制
#include <iostream>
#include <string>

using namespace std;

void remodel(string & str){
    string * ps = new string(str);
    ps[0] = 'n';
    cout<<*ps<<endl;
    delete ps;
}

int main(){
    string str = "Hello world";

    remodel(str);

    cin.get();
    return 0;
}

输出

代码语言:javascript
复制
n

在上面的代码中,对索引0使用[]运算符将整个字符串替换为字母'n‘。这在调试器中得到了确认,在调试器中我可以看到值从"Hello world“到"n”的完全重新分配。

为了详细说明,如果我设置一个断点,使程序在执行ps = 'n‘之前停止,那么在inspecting the variable ps上,它似乎存储了一个用于访问字符串"Hello world“的地址。但是,在执行此行之后,相同的地址只能用于到达字符串/字符"n“。

我的假设是,使用[]运算符会导致在指定的index..but后面放置一个空字符,但我无法确认这一点。

例如,在上面使用ps的代码中,我尝试打印ps1,ps2只是为了看看会发生什么。

我在输出中得到的要么是看起来像空格的无休止(空)输出,要么是一堆胡言乱语。我的空字符假设似乎不是这样的。为了更好地衡量,我还试图手动将一个空字符放在某个位置,比如ps10,但是得到了一个以前分配给我的字符串的分段fault..the内存已经超出了界限!

所以,看起来我需要在这个话题上好好复习一下,有人能解释一下发生了什么吗?请随时让我知道,如果这个问题是含糊的或表达不佳,我会尽我最大的努力来解决它。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-06-05 03:49:35

你的第二个程序格式不正确。它根本没有使用std::string::operator[]

代码语言:javascript
复制
string * ps = new string(str);
ps[0] = 'n';

std::string不仅支持[]运算符,每个指向类型的指针也支持[]运算符。这就是C样式数组的工作方式,也是你在上面的代码中所做的。

ps不是string。这是一个指针。和*ps一样,ps[0]是唯一的字符串。

您可能希望使用this

代码语言:javascript
复制
#include <iostream>
#include <string>

using namespace std;

void remodel(string & str){
    string * ps = new string(str);
    (*ps)[0] = 'n';
    // or: ps->operator[](0) = 'n';
    cout<<*ps<<endl;
    delete ps;
}

int main(){
    string str = "Hello world";

    remodel(str);

    cin.get();
    return 0;
}

或者,更通俗地说,使用this

代码语言:javascript
复制
#include <iostream>
#include <string>

using namespace std;

void remodel(string & str){
    string ps = str;
    ps[0] = 'n';
    cout<<ps<<endl;
}

int main(){
    string str = "Hello world";

    remodel(str);

    cin.get();
    return 0;
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50687711

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档