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

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

    If you don't want to use boost, but want to enjoy syntax like

    std::vector v;
    v+=1,2,3,4,5;
    

    just include this chunk of code

    template  class vector_inserter{
    public:
        std::vector& v;
        vector_inserter(std::vector& v):v(v){}
        vector_inserter& operator,(const T& val){v.push_back(val);return *this;}
    };
    template  vector_inserter operator+=(std::vector& v,const T& x){
        return vector_inserter(v),x;
    }
    

提交回复
热议问题