NoSenseEtAl
NoSenseEtAl

Reputation: 30028

is there a way in c++ to inititialize an array of some class objects without defining the size first

I use code like this:

const vector<filterStat> someArray={
        {"Ana",1},
        {"Bob",2},
        {"Charlie",5},
};
static const int knElements=filterStats.size();

Ignore the kn prefix, it is my way of saying constant, size. I found it useful because I don;t have to change or calculate knElements when I change the initialization of the vector. But the problem is that using a const vector bothers me because vector is resizable array so it feels wrong. BTW if you are wondering why I need it-long story, it's kind of a map, but I dont do any searching or inserting, just "for each" so array is the best choice.

EDIT: I changed my cod to this and it compiles:

const   filterStat filterStats[]={
//...
};

static const int knFilterStats=sizeof(filterStats)/sizeof(filterStats[0]);
static_assert(sizeof(filterStats),"Can't run statistics-no filterStats exists");

I had no idea that you can do [] in c++. Sorry for stupid question, I hope it helps somebody.

Upvotes: 3

Views: 115

Answers (2)

user2100815
user2100815

Reputation:

A const vector is a perfectly good thing to have - your code is the right way to do things.

Upvotes: 2

Bj&#246;rn Pollex
Bj&#246;rn Pollex

Reputation: 76788

You are looking for std::array:

const std::array<filterStat, 3> = {
    {"Ana",1},
    {"Bob",2},
    {"Charlie",5},
};

However, you do have to specify the size.

Upvotes: 5

Related Questions