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

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

    A more recent duplicate question has this answer by Viktor Sehr. For me, it is compact, visually appealing (looks like you are 'shoving' the values in), doesn't require c++11 or a third party module, and avoids using an extra (written) variable. Below is how I am using it with a few changes. I may switch to extending the function of vector and/or va_arg in the future intead.


    // Based on answer by "Viktor Sehr" on Stack Overflow
    // https://stackoverflow.com/a/8907356
    //
    template 
    class mkvec {
    public:
        typedef mkvec my_type;
        my_type& operator<< (const T& val) {
            data_.push_back(val);
            return *this;
        }
        my_type& operator<< (const std::vector& inVector) {
            this->data_.reserve(this->data_.size() + inVector.size());
            this->data_.insert(this->data_.end(), inVector.begin(), inVector.end());
            return *this;
        }
        operator std::vector() const {
            return data_;
        }
    private:
        std::vector data_;
    };
    
    std::vector    vec1;
    std::vector    vec2;
    
    vec1 = mkvec() << 5 << 8 << 19 << 79;  
    // vec1 = (5,8,19,79)
    vec2 = mkvec() << 1 << 2 << 3 << vec1 << 10 << 11 << 12;  
    // vec2 = (1,2,3,5,8,19,79,10,11,12)
    

提交回复
热议问题