Reputation: 5203
I have a struct with 2 std::vector
s as given below. I want to initialize the vector with 2048 elements having initial value 0.0.
struct PixelMaps
{
vector<double> pixelMapX;
vector<double> pixelMapY;
};
I tried the following code. This creates the vector of 2 elements only. How can I initialize the structure with 2048 elements in a single statement with initialization list?
PixelMaps test{ {2048,0.0}, {2048, 0.0} };
Upvotes: 1
Views: 458
Reputation: 14876
Depending on your C++ taste, in C++20 you could write
#include <vector>
struct PixelMaps
{
std::vector<double> pixelMapX;
std::vector<double> pixelMapY;
};
int main()
{
PixelMaps test {
.pixelMapX {std::vector(2048,0.0)},
.pixelMapY {std::vector(2048,0.0)}
};
}
This is known as designated initialization.
Upvotes: 3
Reputation: 22219
std::vector
has a constructor using std::initializer_list
, so you can't use brace-init-list - it will always end up in that constructor. You need more explicit initialization:
PixelMaps test{ std::vector(2048,0.0), std::vector(2048, 0.0) };
Or (pre C++17)
PixelMaps test{ std::vector<double>(2048,0.0), std::vector<double>(2048, 0.0) };
Upvotes: 4