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

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

    If you want something on the same general order as Boost::assign without creating a dependency on Boost, the following is at least vaguely similar:

    template
    class make_vector {
        std::vector data;
    public:
        make_vector(T const &val) { 
            data.push_back(val);
        }
    
        make_vector &operator,(T const &t) {
            data.push_back(t);
            return *this;
        }
    
        operator std::vector() { return data; }
    };
    
    template 
    make_vector makeVect(T const &t) { 
        return make_vector(t);
    }
    

    While I wish the syntax for using it was cleaner, it's still not particularly awful:

    std::vector x = (makeVect(1), 2, 3, 4);
    

提交回复
热议问题