我的C++程序里有一个查找表,目前我需要在程序开始时使用类似这样的方法进行初始化: static const map<string, int> m; m["a"] = 1; m["b"] = 2; ... 我在想是否有办法使这个初始化过程在编译时发生而不是运行时?我知道这对我的程序的性能影响非常小。我只是好奇在当前C++11/14/17语义的范围内是否可能。
不,你不能在编译时初始化std::map! 但是,如果你愿意使用这种“更高级”的初始化方法,那么你可以将数据放在一个const std::map中,以防这正是你想要做的事情。 static const map<string, int> m = { { "a", 1 }, { "b", 2 } }; 但是,这仅仅会在编译时初始化std::map类型本身,背后的操作是在运行时完成的。
static const map<string, int> m{{"a", 1}, {"b", 2}};
但它仍然在运行时。 - Jarod42std::array<std::pair<string, int>, xx>
,但是你不能在constexpr
中使用 map。 - Hatted Rooster