我正在写一个日期类,我想要一个静态地图将"Jan"映射到1,依此类推.我想知道如何初始化静态地图.这就是我目前正在做的事情,但我只是觉得与Java中的静态块相比,额外的if语句是不优雅的.我理解C++程序的编译要复杂得多,但我仍然想知道是否存在更好的解决方案.
class date {
static map<string, int> month_map;
int month;
int year;
public:
class input_format_exception {};
date(const string&);
bool operator< (const date&) const;
string tostring() const;
};
map<string, int> date::month_map = map<string,int>();
date::date(const string& s) {
static bool first = true;
if (first) {
first = false;
month_map["Jan"] = 1;
month_map["Feb"] = 2;
month_map["Mar"] = 3;
month_map["Apr"] = 4;
month_map["May"] = 5;
month_map["Jun"] = 6;
month_map["Jul"] = 7;
month_map["Aug"] = 8;
month_map["Sep"] = 9;
month_map["Oct"] = 10;
month_map["Nov"] = 11; …Run Code Online (Sandbox Code Playgroud) 我有一个枚举,其中包含数百个条目.
我将获取枚举的值作为字符串.有没有办法将字符串转换为枚举值?否则,我将最终使用数百个if语句.
考虑
enum Colors { Red, Green, Blue, Yellow ... } there are more than 100 entries
Run Code Online (Sandbox Code Playgroud)
我将进入"Red"一个字符串变量,
String color = "Red"; // "Red" would be generated dynamically.
Run Code Online (Sandbox Code Playgroud)
通常我们通过以下方式访问枚举
Colors::Red,Colors::Blue等等......有没有什么方法可以让我们以这样的方式访问它:
Colors::color; // i.e enumtype::stringVariable
Run Code Online (Sandbox Code Playgroud)
在这里的许多帖子中,我们可以使用地图,但在构建地图时,我们最终会使用数百个if.
有什么方法可以避免这种情况吗?
我无法理解为什么这不会编译:
#include <map>
#include <string>
std::map<std::string, std::string> m;
m["jkl"] = "asdf";
Run Code Online (Sandbox Code Playgroud)
我收到此编译器错误:
Line 5: error: expected constructor, destructor, or type conversion before '=' token
compilation terminated due to -Wfatal-errors.
我发誓我必须在这里遗漏一些简单的东西.
我想静态初始化一个map<string, pair<some_enum, string> >.让我们说一个从员工ID到职位(枚举)+名称的地图.
我希望它看起来像这样:
map<string, pair<some_enum, string> > = {
{ "1234a", { BOSS, "Alice" }},
{ "5678b", { SLAVE, "Bob" }},
{ "1111b", { IT_GUY, "Cathy" }},
};
Run Code Online (Sandbox Code Playgroud)
在C++中执行此操作的最佳方法是什么?
我需要一种方法来为C++中的字母分配数字,例如,'$'代表数字1.我显然需要能够从类似函数的字符中获取数字,例如getNumFromChar('$')返回1并 getNumFromChar('#')返回2.是有一种简单快捷的方法在C++中执行此操作吗?
map<string, string> info;
info["name"] = "something";
info["id"] = "5665";
Run Code Online (Sandbox Code Playgroud)
在C++中初始化这样的地图有什么更好的方法?
编辑:我想这样做没有任何c ++库或额外的代码.像这样的东西:
info["name", "id"] = {"something", "5665"};
Run Code Online (Sandbox Code Playgroud)