书上说,以下代码创建的对象包含多次的指定字符,重复次数由计数器指定
请问这是怎么回事?,括号里的直接初始化(10,‘9’)是什么意思?
std:string all_nines(10,'9');//all_nines="9999999999"
PHPz2017-04-17 13:30:11
The constructor of std::string
is called here. You can understand the form of this constructor as std::string(count, ch);
, that is, the first parameter is the number of repeated characters, and the second parameter is the character used for repetition. . For example:
std::string s1(4, 'a'); // s1 为 "aaaa"
std::string s2(5, '-'); // s2 为 "-----"
Actually std::string
is the alias (std::basic_string
) of this template class typedef
under specific parameters:
typedef basic_string<char, char_traits<char>, allocator<char>> string;
And the real constructor is
basic_string( size_type count,
CharT ch,
const Allocator& alloc = Allocator() );
The third parameter has a default value and does not need to be provided when calling, thus converting it into std::string(count, ch);
.
高洛峰2017-04-17 13:30:11
is a constructor of string
. The first parameter 10
represents how many characters there are, and the second parameter '9'
represents the initial value of these characters.
Similarly, vector<int> arr(100, 0)
represents a 100
with a size of 0
and all elements are initialized to vector
.