Screenplay: std::map
Initialization And Inserting¶
Definining The Type¶
Inline as you need it
#include <map> #include <string> #include <iostream> int main() { std::map<int, std::string> my_map; // <--- much typing (if done repeatedly) std::cout << my_map.size() << std::endl; return 0; }
Better, mostly, using
using
#include <map> #include <string> #include <iostream> using MyMap = std::map<int, std::string>; int main() { MyMap my_map; // <--- more readable, at least std::cout << my_map.size() << std::endl; return 0; }
Ah, member types
#include <map> #include <string> #include <iostream> using MyMap = std::map<int, std::string>; int main() { MyMap my_map; MyMap::key_type k{666}; // <--- same as "int k{666};" MyMap::mapped_type v{"sechshundersechsundsechzig"}; // <--- same as "std::string v{...};" MyMap::value_type kv{666, "sechshundersechsundsechzig"}; // <--- same as "std::pair<...>{666, ...};" // avoid "unused" warnings (void)k; (void)v; (void)kv; return 0; }
Initialization¶
Pre C++11, there is only default ctor
Elements are added at runtime, using
push_back()
#include <map> #include <string> #include <iostream> using MyMap = std::map<int, std::string>; // <--- pre C++11 has no "using" int main() { MyMap my_map; // <--- pre C++11, there is only default initialization my_map[2] = "zwei"; my_map[51] = "einundfuenfzig"; my_map[54] = "vierundfuenfzig"; my_map[346] = "dreihundertsechsundvierzig"; my_map[1001] = "tausendeins"; my_map[1002] = "tausendzwei"; std::cout << my_map.size() << std::endl; return 0; }
⟶
const
non-default-constructed object#include <map> #include <string> #include <iostream> using MyMap = std::map<int, std::string>; int main() { const MyMap my_map = { // <--- this is *initialization*, hence can be const { 2, "zwei" }, // <--- value_type: std::pair<int, std::string> { 51, "einundfuenfzig" }, // <--- value_type: std::pair<int, std::string> { 54, "vierundfuenfzig" }, // <--- value_type: std::pair<int, std::string> { 346, "dreihundertsechsundvierzig" },// <--- value_type: std::pair<int, std::string> { 1001, "tausendeins" }, // <--- value_type: std::pair<int, std::string> { 1002, "tausendzwei" }, // <--- value_type: std::pair<int, std::string> }; std::cout << my_map.size() << std::endl; return 0; }