Search code examples
c++listc++17stdvector

creating a list of type vectors of fixed size


i want a list of type vector with vector size=3

i tried writing

typedef vector<int> vec; list<vec(3)> q;

but it gave me this error

sol.cpp:22:12: error: temporary of non-literal type ‘vec’ {aka ‘std::vector<int>’} in a constant expression
   22 |       list<vec(3)> q;
      |            ^~~~~~
In file included from /usr/include/c++/11/vector:67,
                 from /usr/include/c++/11/functional:62,
                 from /usr/include/c++/11/pstl/glue_algorithm_defs.h:13,
                 from /usr/include/c++/11/algorithm:74,
                 from /usr/include/x86_64-linux-gnu/c++/11/bits/stdc++.h:65,
                 from sol.cpp:3:
/usr/include/c++/11/bits/stl_vector.h:389:11: note: ‘std::vector<int>’ is not literal because:
  389 |     class vector : protected _Vector_base<_Tp, _Alloc>
      |           ^~~~~~

Solution

  • If you actually want a list of std::vector<int> with size 3, you just need to create a list of std::vector<int> and then construct each vector with size 3. For example, the following line creates a list of 4 vectors each of which has size 3:

    std::list<std::vector<int>> ls(4, std::vector<int>(3));
    

    However, there is nothing to prevent you from changing the size of these vectors or adding more vectors to the list with a size other than 3. If you want a compile-time guarantee that every object in this list should have size 3, then you should use std::array instead of std::vector. For example, the following line creates an empty list of arrays of size 3:

    std::list<std::array<int, 3>> ls;