c++中的String T(a,b)是什么?



当我学习C++时,我挑战了样本问题,其中stdin中的每个1将在stdout中移动。在样本答案中,定义了T(4,0)。由于我是初学者,我不能理解什么是T(4,0)。这和普通数组有什么不同吗?由于

样本回答

#include<bits/stdc++.h>
using namespace std;
int main(){
string S;
cin >> S;
string T(4,0);
T[0]='0';
T[1]=S[0];
T[2]=S[1];
T[3]=S[2];
cout << T;
}

std::string有几个构造函数。在本例中:

basic_string( size_type count, CharT ch, const Allocator& alloc = Allocator() );

(您没有为alloc提供参数,因此使用默认值。别担心。)

这个构造函数有以下作用:

  1. 用字符chcount副本构造字符串。如果要推断的Allocator类型不符合分配器的条件,则不使用此构造函数进行类模板实参推导。(因为C + + 17)]

因此,这创建了一个std::string,其中包含4个字符,每个字符都是0,又名'',又名null。

因为Tstd::string,所以它是std::string的构造函数https://en.cppreference.com/w/cpp/string/basic_string/basic_string

在本例中,它是下的构造函数2):

basic_string( size_type count, CharT ch,
const Allocator& alloc = Allocator() );

(alloc是默认参数,不需要您提供)
它创建一个包含count字符的字符串,每个字符初始化为ch

在你的例子中,它是一个4个字符的字符串,所有初始化为0的任何ascii值。字符

最新更新