Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++, can I statically initialize a std::map at compile time?

Tags:

c++

embedded

stl

If I code this

std::map<int, char> example = {                                 (1, 'a'),                                 (2, 'b'),                                 (3, 'c')                                }; 

then g++ says to me

deducing from brace-enclosed initializer list requires #include <initializer_list> in C++98 ‘example’ must be initialized by constructor, not by ‘{...}’    

and that annoys me slightly because the constructor is run-time and can, theoretically fail.

Sure, if it does, it will fail quickly and ought to do so consistently, so that I ought to quickly locate & correct the problem.

But, still, I am curious - is there anyway to initialize map, vector, etc, at compile time?


Edit: I should have said that I am developing for embedded systems. Not all processors will have a C++0x compiler. The most popular probably will, but I don't want to encounter a gotcha & have to maintain 2 versions of the code.

As to Boost, I am undecided. They are wishy-washy on the use of their Finite State Machine classes in embedded systems, so that is actually what I am coding here, Event/State/Fsm classes.

Sigh, I guess I'd better just play it safe, but I hope that this discussion has been helpful for others.

like image 507
Mawg says reinstate Monica Avatar asked Jan 31 '10 14:01

Mawg says reinstate Monica


People also ask

Do we need to initialize map in C++?

A map is a container which is used to store a key-value pair. By default, In Primitive datatypes such as int, char, bool, float in C/C++ are undefined if variables are not initialized, But a Map is initially empty when it is declared.

Is std::map ordered?

Yes, a std::map<K,V> is ordered based on the key, K , using std::less<K> to compare objects, by default.

Are Maps slow C++?

Maps are 'fast enough' but not brilliant for some cases. Try to analyze what is the structure of objects you need to store. If the fields are fixed I'd recommend not to use nested maps. At all.


1 Answers

It's not exactly static initialization, but still, give it a try. If your compiler doesn't support C++0x, I'd go for std::map's iteration constructor:

std::pair<int, std::string> map_data[] = {     std::make_pair(1, "a"),     std::make_pair(2, "b"),     std::make_pair(3, "c") };  std::map<int, std::string> my_map(map_data,     map_data + sizeof map_data / sizeof map_data[0]); 

This is pretty readable, doesn't require any extra libraries and should work in all compilers.

like image 175
Dmitry Avatar answered Oct 15 '22 02:10

Dmitry