0

I'm trying to initialize a vector in a header with the following code, but getting the error

C2552: 'LABELS' : non-aggregates cannot be initialized with initializer list.

I searched the reason is that VS2010 does not support C++11 initializer lists.

How can I initialize the vector in VS2010?

const int CLEAN = 0;
const int TARGET = 1; 
const vector<int> LABELS = { CLEAN, TARGET };
bummi
  • 27,123
  • 14
  • 62
  • 101
TieZhu
  • 1
  • 1
    You could consider upgrading your IDE/compiler rather than sticking with something that's a decade old by now. – Jesper Juhl May 05 '19 at 13:01
  • No issue in `g++`: [Live Demon on coliru](http://coliru.stacked-crooked.com/a/11d5b9e1ec82c0e9) Might be a weakness of VS2010. – Scheff's Cat May 05 '19 at 13:01
  • May be, an "intermediate" array could be a workaround: [Live Demo on coliru](http://coliru.stacked-crooked.com/a/8545674712f3109b) (but I had no VS2010 at hand to check it there...) – Scheff's Cat May 05 '19 at 13:04
  • 1
    You can fix all the problems of VS2010 with one simple uninstall. – n. m. could be an AI May 05 '19 at 13:07
  • Explicitly push back each value? – Some programmer dude May 05 '19 at 13:08
  • You should initialize array and then vector with it. Or use simple array. https://stackoverflow.com/questions/2236197/what-is-the-easiest-way-to-initialize-a-stdvector-with-hardcoded-elements – a1ezh May 05 '19 at 13:11
  • Thanks for all the replies. The replies of @Scheff and a1ezh works, I tried the method and it can be successfully complied by VS2010. Thanks a lot! – TieZhu May 05 '19 at 13:26

1 Answers1

0

This should work. At least, it is pure C++98

const int CLEAN = 0;
const int TARGET = 1;
const int LABELS_N = 2;
int LABELS_A[LABELS_N] = { CLEAN, TARGET};
const std::vector<int> LABELS(LABELS_A, LABELS_A+LABELS_N);

I'd also recommend you to enclose the additional items in a namespace:

namespace detail {
    const int LABELS_N = 2;
    int LABELS_A[LABELS_N] = { CLEAN, TARGET};
}
const std::vector<int> LABELS(detail::LABELS_A, detail::LABELS_A+detail::LABELS_N);

Another option is using an initializer class, especially if you have many global constants like this:

namespace detail {
    struct Initializer
    {
        Initializer()
        {
            LABELS.push_back(CLEAN);
            LABELS.push_back(TARGET);
        }
        std::vector<int> LABELS;
    };
    const Initializer initializer;
}
const std::vector<int>& LABELS = detail::initializer.LABELS;

And yes, you are likely to have more problems if you don't upgrade your compiler.

aparpara
  • 2,171
  • 8
  • 23