如何使用初始化列表初始化2D矢量成员?

时间:2014-03-02 21:42:05

标签: c++ c++11

我有代码:

#include <initializer_list>
#include <vector>    

class Foo {
    std::vector<std::vector<int> > data;
    public:
    Foo(std::initializer_list<std::initializer_list<int> > & data) : data(data) {}
};

int main(){
    Foo f {{1,2},{3,3}};
    return 0;
}

编译器抱怨:

initalizer_list_test.cpp: In constructor ‘Foo::Foo(std::initializer_list<std::initializer_list<int> >&)’:
initalizer_list_test.cpp:11:79: error: no matching function for call to ‘std::vector<std::vector<int> >::vector(std::initializer_list<std::initializer_list<int> >&)’
     Foo(std::initializer_list<std::initializer_list<int> > & data) : data(data) {}
                                                                               ^
initalizer_list_test.cpp:11:79: note: candidates are:
In file included from /usr/include/c++/4.8.2/vector:64:0,
                 from initalizer_list_test.cpp:2:
/usr/include/c++/4.8.2/bits/stl_vector.h:392:9: note: template<class _InputIterator, class> std::vector<_Tp, _Alloc>::vector(_InputIterator, _InputIterator, const allocator_type&)
         vector(_InputIterator __first, _InputIterator __last,
         ^
/usr/include/c++/4.8.2/bits/stl_vector.h:392:9: note:   template argument deduction/substitution failed:
initalizer_list_test.cpp:11:79: note:   candidate expects 3 arguments, 1 provided
     Foo(std::initializer_list<std::initializer_list<int> > & data) : data(data) {}

如何让它正常工作?

1 个答案:

答案 0 :(得分:4)

首先,只需使用初始化矢量列表即可初始化2D矢量。然后只是按值而不是引用(初学者列表,据我所知,通常按值传递,非const引用不起作用):

Foo(std::initializer_list<std::vector<int> > data) : data(data) {}