how-to initialize 'const std::vector' like a c array

后端 未结 10 771
走了就别回头了
走了就别回头了 2020-11-27 02:59

Is there an elegant way to create and initialize a const std::vector like const T a[] = { ... } to a fixed (and small) number of val

10条回答
  •  时光取名叫无心
    2020-11-27 03:17

    Based on Shadow2531's response, I'm using this class to initialise vectors, without actually inheriting from std::vector like Shadow's solution did

    template 
    class vector_init
    {
    public:
        vector_init(const T& val)
        {
            vec.push_back(val);
        }
        inline vector_init& operator()(T val)
        {
            vec.push_back(val);
            return *this;
        }
        inline std::vector end()
        {
            return vec;
        }
    private:
        std::vector vec;
    };
    

    Usage:

    std::vector testVec = vector_init(1)(2)(3)(4)(5).end();
    

    Compared to Steve Jessop's solution it creates a lot more code, but if the array creation isn't performance critical I find it a nice way to initialise an array in a single line

提交回复
热议问题