Reputation: 375
I have created the following class:
class A{
public:
static std::map<std::pair<unsigned, unsigned>, unsigned> var1;
};
std::map<std::pair<unsigned, unsigned>, unsigned> A::var1[std::make_pair(0,0)]=0; //it is used to initialize static variable var1 inside A.
However, when I do so I get the following error:
array bound is not an integer constant before ‘]’ token
Is there some way by which I may initialize var1 with some default values?
Upvotes: 2
Views: 285
Reputation: 361
In C++98,you can use a function to inialize your static variable. For example, you can do something like this
typedef std::map<std::pair<unsigned, unsigned>, unsigned> mymap;
mymap init() {
mymap m;
m[std::make_pair(0,0)] = 0;
return m;
}
class A {
public:
static mymap var1;
};
mymap A::var1 = init();
If you can use C++11, it is shorter
std::map<std::pair<unsigned, unsigned>, unsigned> A::var1 = {std::make_pair(std::make_pair(0, 0), 0)};
Upvotes: 0
Reputation: 1420
With C++11
#include <map>
using namespace std;
map<int, char> m = {{{1, 1}, 2}, {{2, 2}, 3}, ...};
Or use boost.assign.
Upvotes: 2
Reputation: 10667
You can't declare your variable and initialize one of its item using A[...]=
at the same time.
std::map<std::pair<unsigned, unsigned>, unsigned> A;
A::var1[std::make_pair(0,0)]=0;
should work. If C++11 you can use bracket initialization as
std::map<std::pair<unsigned, unsigned>, unsigned> A = {{{0,0}, 0}};
Upvotes: 3
Reputation: 87271
static std::map<std::pair<unsigned, unsigned>, unsigned> CreatVar1() {
std::map<std::pair<unsigned, unsigned>, unsigned> var;
var[std::make_pair(0,0)]=0;
return var;
}
std::map<std::pair<unsigned, unsigned>, unsigned> A::var1 = CreateVar1();
Or, alternatively, in C++11:
std::map<std::pair<unsigned, unsigned>, unsigned> A::var1 = {{{0, 0}, 0}};
Upvotes: 3