Reputation:
How to initialize a vector in C++ to some specific size inside constructor with c++11? Something like this (vector called my_vec):
#ifndef MAP_H
#define MAP_H
#include <vector>
struct color
{
int r;
int g;
int b;
};
class map
{
private:
int gridSize;
int verticalNum;
int horizontalNum;
std::vector< std::vector<color> > my_vec(100, vector<color>(100));
public:
map();
~map();
};
#endif // MAP_H
This doesn`t work so I tried this:
#ifndef MAP_H
#define MAP_H
#include <vector>
struct color
{
int r;
int g;
int b;
};
class map
{
private:
int gridSize;
int verticalNum;
int horizontalNum;
std::vector< std::vector<color> > *my_vec;
public:
map();
~map();
};
#endif // MAP_H
and in constructor I tried to initialize it like:
map::map()
{
this->my_vec(100, std::vector<color>(100));
}
But I get an error that : "expression cannot be used as a function"
Upvotes: 1
Views: 4423
Reputation: 42899
You have to do it in the constructor's initializer list:
map::map() : my_vec(100, std::vector<color>(100))
{
}
But you could also initialize it as an in class variable as:
class MyMap {
// ...
std::vector< std::vector<color> > my_vec =
std::vector<std::vector<color>>(100, std::vector<color>(100));
public:
MyMap() {}
~MyMap() {}
};
Upvotes: 2
Reputation: 456
As you just specified C++11, in-class initialzation may be exactly what you want:
private:
std::vector<std::vector<color>> my_vec = std::vector<std::vector<color>>(100, std::vector<color>(100));
Upvotes: 7
Reputation: 409176
You need to use a constructor initializer list
map::map()
: my_vec(100, std::vector<color>(100))
{}
However, if the actual code have a compile-time hard-coded size, why not use std::array
instead? Like
std::array<std::array<color, 100>, 100> my_vec;
Upvotes: 1