-7

How may I define a vector in C++11 such that its size is 4*5 so I can treat it like a matrix? (I mean using operator [] like the following)

mat[2][3];

Update: The following gives me error:

#include <memory>
class Test{
        std::vector<int> vect;
};

Error message:

implicit instantiation of undefined template 'std::__1::vector<int, std::__1::allocator<int> >'
    std::vector<int> vect;

2 Answers2

3

You just need a nested vector, like this:

auto v = std::vector<std::vector<int>>(4, std::vector<int>(5));

and you can then index it like v[0][0].

cigien
  • 57,834
  • 11
  • 73
  • 112
  • can't I create it as one single vector (for efficency) –  Jun 24 '20 at 13:21
  • Yes, of course. Did you see the link that was posted in the comments? See the dupe target. – cigien Jun 24 '20 at 13:22
  • But I'm getting an error: implicit instantiation of undefined template 'std::__1::vector >' std::vector vect; when I type std::vector vect; –  Jun 24 '20 at 13:27
  • 1
    Ok, then update the question with what you've tried, and show a minimal reproducible example. – cigien Jun 24 '20 at 13:30
  • Done that, take a look if possible –  Jun 24 '20 at 13:41
0

The error implicit instantiation of undefined template std::__1::vector ... means std::vector is unknown to the compiler.

You need to #include <vector>

rustyx
  • 80,671
  • 25
  • 200
  • 267