Mario
Mario

Reputation: 322

How to default initilise a std::vector

Trying to default initialize a std::vector

#include <iostream>
#include <vector>
int main()
{    
    class Options
    {
        std::vector<int> items{100};
    } options ;

    std::cout << "Size:" << options.items.size() << " Items[0]:" << options.items[0] << '\n';

    return 0;
 }

This will print:

Size 1 : Items[0]:100

But that is not what I want, I want the vector to be of size 100.

I managed to do it with

class Options
{
    std::vector<int> items{ std::vector<int>(100) };
} options ;

But I get the feeling there must be a "better" way?

Regards,

Upvotes: 5

Views: 658

Answers (4)

Tobias
Tobias

Reputation: 845

To avoid any confusion due to differing behavior between

std::vector<int> items(100);

and

std::vector<int> items{100};

use

std::vector<int> items;
items.resize(100);       //Default initializes 100 int <=> zero
// or
items.resize(100, 17);   //Initializes 100 ints with value 17

Used in a constructor

class Options
{
    std::vector<int> items;

public:
    Options()
    {
        items.resize(100);
    }
} options;

Upvotes: 4

divyang4481
divyang4481

Reputation: 1783

change your code as follows :

std::vector<int> items(100,0);

This will create vector with size 100 and initialized all with value 0

Upvotes: 0

Mooing Duck
Mooing Duck

Reputation: 66952

class Options
{
    std::vector<int> items;
public: 
    Options() : items(100) {}
}

The : starts the list initialization of the members, constructing the members in the order they're declared in the class, before the constructor body starts.

Upvotes: 0

NathanOliver
NathanOliver

Reputation: 180935

The only way to initialize a class member in the body of the class is to brace or equal initialize it. That means you can do

std::vector<int> items{ std::vector<int>(100) };

or

std::vector<int> items = std::vector<int>(100);

If you don't like either of those options then you can add an initializer to the classes constructor and have

class Options
{
    Options() : items(100) {}
    std::vector<int> items;
} options ;

but personally I would use the first two options instead.

Upvotes: 7

Related Questions