Reputation: 13
I would like to initialize a 2d vector but I keep getting an error message
if I write this code
unsigned long size = 101;
double initialmPo = 63;
std::vector<std::vector<Soil> > matrixPotential(
size, std::vector<Soil>(size));
I do not have a problem but if I write this code
std::vector<std::vector<Soil> > matrixPotential(
size, std::vector<Soil>(size, initialmPo));
I get the message of
no matching constructor for initialization of std::vector< Soil >
I would like to have a 101*101 vector and inside of vector is the value(number) of 63.
And that is my class Soil
class Soil
{
public:
Soil();
double A;
double B;
double C;
double D;
};
#endif // SOIL_H
What should I do?
Upvotes: 0
Views: 154
Reputation: 7539
Your code does not work because initialmPo
is not a valid Soil
instance. The constructor of std::vector
you need is
explicit vector( size_type count,
const T& value = T(),
const Allocator& alloc = Allocator()); (until C++11)
vector( size_type count,
const T& value,
const Allocator& alloc = Allocator()); (since C++11)
For this to work you should pass the desired Soil
element as a second parameter. In your class, you should define a constructor that takes care of initializing the fields with the desired value(s). Or you should eliminate the parameterless constructor and opt for an aggregate initialization.
Example (with constructor)
#include <vector>
class Soil
{
public:
double A;
double B;
double C;
double D;
Soil(double in) : A{in}, B{in}, C{in}, D{in} { }
};
int main()
{
unsigned long size = 101;
double initialmPo = 63;
Soil s(initialmPo);
std::vector<std::vector<Soil> > matrixPotential(
size, std::vector<Soil>(size, s));
return 0;
}
See it live
Example (with aggregate initialization)
#include <vector>
class Soil
{
public:
double A;
double B;
double C;
double D;
};
int main()
{
unsigned long size = 101;
double initialmPo = 63;
Soil s{initialmPo, initialmPo, initialmPo, initialmPo};
std::vector<std::vector<Soil> > matrixPotential(
size, std::vector<Soil>(size, s));
return 0;
}
See it live
Upvotes: 1