What is the easiest way to initialize a std::vector with hardcoded elements?

后端 未结 29 3097
终归单人心
终归单人心 2020-11-22 05:07

I can create an array and initialize it like this:

int a[] = {10, 20, 30};

How do I create a std::vector and initialize it sim

29条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-22 05:43

    I build my own solution using va_arg. This solution is C++98 compliant.

    #include 
    #include 
    #include 
    
    template 
    std::vector initVector (int len, ...)
    {
      std::vector v;
      va_list vl;
      va_start(vl, len);
      for (int i = 0; i < len; ++i)
        v.push_back(va_arg(vl, T));
      va_end(vl);
      return v;
    }
    
    int main ()
    {
      std::vector v = initVector (7,702,422,631,834,892,104,772);
      for (std::vector::const_iterator it = v.begin() ; it != v.end(); ++it)
        std::cout << *it << std::endl;
      return 0;
    }
    

    Demo

提交回复
热议问题