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

后端 未结 29 2527
终归单人心
终归单人心 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:47

    If your compiler supports C++11, you can simply do:

    std::vector v = {1, 2, 3, 4};
    

    This is available in GCC as of version 4.4. Unfortunately, VC++ 2010 seems to be lagging behind in this respect.

    Alternatively, the Boost.Assign library uses non-macro magic to allow the following:

    #include 
    ...
    std::vector v = boost::assign::list_of(1)(2)(3)(4);
    

    Or:

    #include 
    using namespace boost::assign;
    ...
    std::vector v;
    v += 1, 2, 3, 4;
    

    But keep in mind that this has some overhead (basically, list_of constructs a std::deque under the hood) so for performance-critical code you'd be better off doing as Yacoby says.

提交回复
热议问题