Which greedy initializer-list examples are lurking in the Standard Library?

前端 未结 2 1247
余生分开走
余生分开走 2020-12-03 01:38

Since C++11, the Standard Library containers and std::string have constructors taking an initializer-list. This constructor takes precedence over other construc

相关标签:
2条回答
  • 2020-12-03 02:20

    I assume, with your examples for std::vector<int> and std::string you meant to also cover the other containers, e.g., std::list<int>, std::deque<int>, etc. which have the same problem, obviously, as std::vector<int>. Likewise, the int isn't the only type as it also applies to char, short, long and their unsigned version (possibly a few other integral types, too).

    I think there is also std::valarray<T> but I'm not sure if T is allowed to be integral type. Actually, I think these have different semantics:

    std::valarray<double>(0.0, 3);
    std::valarray<double>{0.0, 3};
    

    There are a few other standard C++ class templates which take an std::initializer_list<T> as argument but I don't think any of these has an overloaded constructor which would be used when using parenthesis instead of braces.

    0 讨论(0)
  • 2020-12-03 02:40

    Just searching for the occurence of initializer_list.

    • All sequences, they are have the constructors like that of vector:

      • deque
      • dynarray
      • forward_list
      • list
      • vector
    • valarray

    • basic_string

    • Unordered collections, there is a constructor which takes an integer to determine the initial bucket count.

      • unordered_set
      • unordered_multiset

    I think that's all of it.

    #include <unordered_set>
    #include <iostream>
    
    int main() {
        std::unordered_set<int> f (3);
        std::unordered_set<int> g {3};
        std::cout << f.size() << "/" << g.size() << std::endl; // prints 0/1.
    }
    
    0 讨论(0)
提交回复
热议问题