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

后端 未结 10 772
走了就别回头了
走了就别回头了 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:39

    Short and dirty way (similar to Boost's list_of())

    #include 
    #include 
    #include 
    #include 
    using namespace std;
    
    template 
    struct vlist_of : public vector {
        vlist_of(const T& t) {
            (*this)(t);
        }
        vlist_of& operator()(const T& t) {
            this->push_back(t);
            return *this;
        }
    };
    
    int main() {
        const vector v = vlist_of(1)(2)(3)(4)(5);
        copy(v.begin(), v.end(), ostream_iterator(cout, "\n"));
    }
    

    Now, C++11 has initializer lists, so you don't need to do it that way or even use Boost. But, as an example, you can do the above in C++11 more efficiently like this:

        #include 
        #include 
        #include 
        #include 
        using namespace std;
    
        template 
        struct vlist_of : public vector {
            vlist_of(T&& t) {
                (*this)(move(t));
            }
            vlist_of& operator()(T&& t) {
                this->push_back(move(t));
                return *this;
            }
        };
    
        int main() {
            const vector v = vlist_of(1)(2)(3)(4)(5);
            for (const auto& i: v) {
                cout << i << endl;
            }
        }
    

    But, it's still not as efficient as using a C++11 initializer list because there's no operator=(vlist_of&&) defined for vector.

    tjohns20's way modified like the following might be a better c++11 vlist_of:

    #include 
    #include 
    #include 
    using namespace std;
    
    template 
    class vlist_of {
        public:
            vlist_of(T&& r) {
                (*this)(move(r));
            }
            vlist_of& operator()(T&& r) {
                v.push_back(move(r));
                return *this;
            }
            vector&& operator()() {
                return move(v);
            }
        private:
            vector v;
        
    };
    
    int main() {
        const auto v = vlist_of(1)(2)(3)(4)(5)();
        for (const auto& i : v) {
            cout << i << endl;
        }
        
    }
    

提交回复
热议问题