Maanu
Maanu

Reputation: 5203

Initialize std::vector in a struct

I have a struct with 2 std::vectors 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

Answers (2)

Tony Tannous
Tony Tannous

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

Yksisarvinen
Yksisarvinen

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

Related Questions