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

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

    B. Stroustrup describes a nice way to chain operations in 16.2.10 Selfreference on page 464 in the C++11 edition of the Prog. Lang. where a function returns a reference, here modified to a vector. This way you can chain like v.pb(1).pb(2).pb(3); but may be too much work for such small gains.

    #include 
    #include 
    
    template
    class chain
    {
    private:
        std::vector _v;
    public:
        chain& pb(T a) {
            _v.push_back(a);
            return *this;
        };
        std::vector get() { return _v; };
    };
    
    using namespace std;
    
    int main(int argc, char const *argv[])
    {
        chain v{};
    
        v.pb(1).pb(2).pb(3);
    
        for (auto& i : v.get()) {
            cout << i << endl;
        }
    
        return 0;
    }
    

    1
    2
    3

提交回复
热议问题