liuxiaolong
2021-07-20 58d904a328c0d849769b483e901a0be9426b8209
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#ifndef APP_ARG_OQMELZBX
#define APP_ARG_OQMELZBX
 
#include <map>
#include <string>
 
class AppArg
{
    typedef std::map<std::string, std::string> ArgMap;
public:
    AppArg(int argc, const char *argv[]) {
        Parse(argc, argv);
    }
    bool Has(const std::string &key) const {
        return Pos(key) != args.end();
    }
    std::string Get(const std::string &key, const std::string &def = "") const {
        ArgMap::const_iterator pos = Pos(key);
        if (pos != args.end()) {
            return pos->second;
        } else {
            return def;
        }
    }
private:
    void Parse(int argc, const char *argv[]) {
        for (int i = 1; i < argc; ++i) {
            std::string text(argv[i]);
            if (text.substr(0, 2) == "--") {
                text = text.substr(2);
                std::string::size_type sep = text.find('=');
                if (sep == std::string::npos) {
                    args[text].clear();
                } else {
                    args[text.substr(0, sep)] = text.substr(sep+1);
                }
            } else if (text.substr(0,1) == "-") {
                text = text.substr(1);
                args[text].clear();
                if (i+1 < argc) {
                    std::string next(argv[i+1]);
                    if (next.substr(0,1) != "-") {
                        args[text] = next;
                        ++i;
                    }
                }
            }
        }
        
    }
    ArgMap::const_iterator Pos(const std::string &key) const {
        return args.find(key);
    }
 
    ArgMap args;
};
 
#endif // end of include guard: APP_ARG_OQMELZBX