search

Home  >  Q&A  >  body text

c++prime 中提到的用计数器初始化对象

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

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

reply all(3)I'll reply

  • PHPz

    PHPz2017-04-17 13:30:11

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

    reply
    0
  • 巴扎黑

    巴扎黑2017-04-17 13:30:11

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

    reply
    0
  • 高洛峰

    高洛峰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.

    reply
    0
  • Cancelreply