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

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

    Just thought I'd toss in my $0.02. I tend to declare this:

    template< typename T, size_t N >
    std::vector makeVector( const T (&data)[N] )
    {
        return std::vector(data, data+N);
    }
    

    in a utility header somewhere and then all that's required is:

    const double values[] = { 2.0, 1.0, 42.0, -7 };
    std::vector array = makeVector(values);
    

    But I can't wait for C++0x. I'm stuck because my code must also compile in Visual Studio. Boo.

提交回复
热议问题