当我学习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
提供参数,因此使用默认值。别担心。)
这个构造函数有以下作用:
- 用字符
ch
的count
副本构造字符串。如果要推断的Allocator类型不符合分配器的条件,则不使用此构造函数进行类模板实参推导。(因为C + + 17)]
因此,这创建了一个std::string
,其中包含4
个字符,每个字符都是0
,又名' '
,又名null。
因为T
是std::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值。