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.
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.
Yes, a std::map<K,V> is ordered based on the key, K , using std::less<K> to compare objects, by default.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With