Can I initialize an STL vector with 10 of the same integer in an initializer list?

后端 未结 6 1720
遇见更好的自我
遇见更好的自我 2021-01-31 07:54

Can I initialize an STL vector with 10 of the same integer in an initializer list? My attempts so far have failed me.

相关标签:
6条回答
  • 2021-01-31 08:02

    You can do that with std::vector constructor:

    vector(size_type count, 
                     const T& value,
                     const Allocator& alloc = Allocator());
    

    Which takes count and value to be repeated.

    If you want to use initializer lists you can write:

    const int x = 5;
    std::vector<int> vec {x, x, x, x, x, x, x, x, x, x};
    
    0 讨论(0)
  • 2021-01-31 08:07

    The initialization list for vector is supported from C++0x. If you compiled with C++98

    int number_of_elements = 10;
    int default_value = 1;
    std::vector<int> vec(number_of_elements, default_value);
    
    0 讨论(0)
  • 2021-01-31 08:08

    Use the appropriate constructor, which takes a size and a default value.

    int number_of_elements = 10;
    int default_value = 1;
    std::vector<int> vec(number_of_elements, default_value);
    
    0 讨论(0)
  • 2021-01-31 08:12

    I think you mean this:

    struct test {
       std::vector<int> v;
       test(int value) : v( 100, value ) {}
    };
    
    0 讨论(0)
  • 2021-01-31 08:14

    If you're using C++11 and on GCC, you could do this:

    vector<int> myVec () {[0 ... 99] = 1};
    

    It's called ranged initialization and is a GCC-only extension.

    0 讨论(0)
  • 2021-01-31 08:22

    can you post what you are doing

     int i = 100;
    vector<int> vInts2 (10, i);
    
    vector<int>::iterator iter;
    for(iter = vInts2.begin(); iter != vInts2.end(); ++iter)
    {
        cout << " i " << (*iter) << endl;
    }
    
    0 讨论(0)
提交回复
热议问题