5

I am trying to create a static const vector of const vectors of ints (there's gotta be a better way to do this) in Visual Studio 2012 and I can't figure out the proper syntax to initialize it with. I believe 2012 uses a version of C++ that doesn't allow initializers but I don't know how else to accomplish what I want.

I've tried the following in 2013, and it seems to compile ok:

.h:

static const std::vector<const std::vector<int>> PartLibrary;

.cpp:

const std::vector<const std::vector<int>> Parts::PartLibrary {
    std::vector<int> { 29434 }, // 1
    std::vector<int> { 26322 }, // 2
...
}

However, when I try the same in 2012, it errors out:

Error   1   error C2470: 'PartLibrary' : looks like a function definition, 
but there is no parameter list; skipping apparent body

How can I properly initialize this? Is there a more appropriate data type out there I can use? I simply want my static class to have a constant vector of vectors of ints so I can quickly read, but not modify, values.

Alex R.
  • 185
  • 1
  • 7
  • Did you compile with c++11 standard option switched on? – πάντα ῥεῖ Nov 24 '14 at 08:10
  • 4
    Visual Studio 2012 does not fully support C++11. Use a more recent version. Or use boost assign to do the static initalization. – tillaert Nov 24 '14 at 08:11
  • @πάνταῥεῖ I don't know how to do that, but a quick google search is telling me that it is enabled by default, but initializer lists were not added to 2012 – Alex R. Nov 24 '14 at 08:15
  • @tillaert unfortunately I have to do 2012. However, I wonder if I can update the compiler to a version with initializer list support – Alex R. Nov 24 '14 at 08:16
  • 1
    Isn't the inner `const` totally useless anyway? You cannot modify the topmost container, thus cannot modify any element of the inner container. – JBL Nov 24 '14 at 09:09
  • I have resorted to using a static 2-dimensional array instead (`static int PartLibrary[35][1];`, and `int Parts::PartLibrary[35][1] = { { 29434 }, // 1 ...};`) because it is sufficient for my needs, though I believe you can update the compiler for 2012 and have access to initializer lists. Because I cannot confirm, I will leave question unanswered. – Alex R. Nov 24 '14 at 09:17

1 Answers1

0

In C++, you can't have a std::vector<const anything>, see for example here. The elements have to be Assignable.

In C++98, you could try the following initialization scheme. It has the disadvantage of copying the vectors from the array to the vector:

const std::vector<int> vectors[2] = {
    std::vector<int> (1, 29434), // vector of one element
    std::vector<int> (1, 26322), // vector of one element
};
const std::vector<std::vector<int> > /*Parts::*/PartLibrary (vectors+0, vectors+2);
// space needed for C++98---------^
Community
  • 1
  • 1
Bulletmagnet
  • 5,665
  • 2
  • 26
  • 56