如果c ++字符串给出相同的输出,那么size()和length()函数有什么区别? [英] what is the difference between size() and length() function of c++ string if they give the same output?

查看:255
本文介绍了如果c ++字符串给出相同的输出,那么size()和length()函数有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,我们如何区分字符串的size()和length()?



In the following code how can we differentiate between size() and length() of string ?

#include<iostream.h>
#include<conio.h>
using namespace std;
int main()
{
   char a[5]="abc";
    
    cout<<sizeof(a);
    cout<<endl;
    
    string s;
    s=a;
    cout<<s.length();
    cout<<endl;
    cout<<s.size();
    cout<<endl;
    
    string b[3];
    cout<<"Size of string :"<<s.size()<<endl;
    b[0]="abcd";
    cout<<"Size of string :"<<s.length();
    getch();
    return 0;
}

推荐答案

正如Wes在评论中回答的......它只是一个别名...



见这里 [ ^ ]



可能存在某种历史原因,为什么有两种方法可以做同样的事情,但在这一点上它确实无关紧要。我建议你在代码中只使用一个版本,因为从长远来看,它会使它更易读,更容易支持(如果他们决定在将来消除其中一个版本,那么它将更容易修复)。
As Wes answered in the comments... it's just an alias...

See here[^]

There's probably some sort of historical reason why there's two methods that do the same exact thing, but it's really irrelevant at this point. I'd recommend you use only one version in your code since it'll make it more readable and easier to support in the long run (if they decide to eliminate one or the other in the future it'll be easier to fix).


也许不是一个严格的正式答案,但我已经看到'size'指的是字节数的约定,'length'指的是元素的数量。因此对于char数组,大小和长度是相同的,但对于其他数据类型的数组,大小会更大。
Maybe not a strictly formal answer, but I've seen the convention that 'size' refers to the number of bytes, and 'length' refers to the number of elements. So for a char array, the size and length are the same, but for arrays of other data types the size would be greater.


这篇关于如果c ++字符串给出相同的输出,那么size()和length()函数有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆