开发者

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

开发者 https://www.devze.com 2023-03-13 06:42 出处:网络
I use code like this: const vector<filterStat> someArray={ {\"Ana\",1}, {\"Bob\",2}, {\"Charlie\",5},

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.


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消