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

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

    There are a lot of good answers here, but since I independently arrived at my own before reading this, I figured I'd toss mine up here anyway...

    Here's a method that I'm using for this which will work universally across compilers and platforms:

    Create a struct or class as a container for your collection of objects. Define an operator overload function for <<.

    class MyObject;
    
    struct MyObjectList
    {
        std::list objects;
        MyObjectList& operator<<( const MyObject o )
        { 
            objects.push_back( o );
            return *this; 
        }
    };
    

    You can create functions which take your struct as a parameter, e.g.:

    someFunc( MyObjectList &objects );
    

    Then, you can call that function, like this:

    someFunc( MyObjectList() << MyObject(1) <<  MyObject(2) <<  MyObject(3) );
    

    That way, you can build and pass a dynamically sized collection of objects to a function in one single clean line!

提交回复
热议问题