3

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.

Johannes Schaub - litb
  • 496,577
  • 130
  • 894
  • 1,212
NoSenseEtAl
  • 28,205
  • 28
  • 128
  • 277
  • 1
    The original code was better, IMHO. –  Jun 14 '11 at 07:49
  • I know and I agree, but the thing is that it is a relatively often called part of the wannabe high performance application, so I prefer to use it this way. BTW when I think about it range based for loop makes knFilterStats unnecessary. :) I just dont know if it is the same speed as the regular for. – NoSenseEtAl Jun 14 '11 at 08:03
  • 1
    The problem with your new code is that you are going to have to pass the size of the array around with the array. You wouldn't have to do that with a vector. –  Jun 14 '11 at 08:06
  • 1
    @Neil: The old code had the specific purpose of passing around the size with the `vector`. Maybe it was unnecessary, but given the decision to create a separate variable for `filterStats.size` the array seems reasonable. – Potatoswatter Jun 14 '11 at 08:11
  • 1
    If you find yourself taking the time to think about such a decision, it's best to just try both ways and measure in a controlled experiment. Usually the array-indexing style is optimized into the pointer-incrementing style, not the other way around, although it can depend. – Potatoswatter Jun 14 '11 at 08:14

2 Answers2

5

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.

Björn Pollex
  • 75,346
  • 28
  • 201
  • 283
  • Or you could use a `make_array` helper [like this one](http://stackoverflow.com/questions/6114067/how-to-emulate-c-array-initialization-int-arr-e1-e2-e3-behaviour/6272491#6272491) and just write `const auto X = make_array({"Ana",1}, {"Bob",2}, {"Charlie",5});". – Kerrek SB Jun 14 '11 at 13:12
  • @Kerrek : Not if he's using MSVC ;-[ – ildjarn Jun 14 '11 at 15:35
2

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