c++prime 中提到的用计数器初始化对象
怪我咯
怪我咯 2017-04-17 13:28:11
0
3
635

书上说,以下代码创建的对象包含多次的指定字符,重复次数由计数器指定

 请问这是怎么回事?,括号里的直接初始化(10,‘9’)是什么意思?
 std:string all_nines(10,'9');//all_nines="9999999999"
  
怪我咯
怪我咯

走同样的路,发现不同的人生

reply all(3)
PHPzhong

Principle of simplification

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 为 "-----"

The actual principle

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);.

巴扎黑

http://en.cppreference.com/w/cpp/string/basic_string/basic_string

小葫芦

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template