Regex and Map

closed account (Ey80oG1T)
Why does this give me an error?

1
2
3
4
5
6
7
8
9
10
    std::map<std::regex, std::string> rgx{
        std::make_pair(std::regex("[0-9]+.[0-9]+"), "FLOAT\n"),
        std::make_pair(std::regex("[0-9]+"), "INT\n"),
        std::make_pair(std::regex("+"), "PLUS\n"),
        std::make_pair(std::regex("-"), "MINUS\n"),
        std::make_pair(std::regex("*"), "TIMES\n"),
        std::make_pair(std::regex("/"), "DIVIDED BY\n"),
        std::make_pair(std::regex(";"), "SEMICOLON\n"),
        std::make_pair(std::regex("[\t\r\n\f]"), "")
    };


It says "binary '<': 'const _Ty' does not define this operator or a conversion to a type acceptable to the predefined operator"
Apparently regex had no operator<, which wouldn't make much sense for it.
You aren't expecting to "index" the map with the regexes, are you?
Presumably your key is FLOAT, INT, etc., so that should come first.

closed account (Ey80oG1T)
Oh, I see. Would an unordered map work then? Since it doesn't use < to sort on insert?
std::map actually allows you to supply a function to compare the keys with. It’s just automatically set to the < operator. You can change it though.

http://cplusplus.com/reference/map/map/?kw=map


1
2
3
4
5
6
7

template < class Key,                                     // map::key_type
           class T,                                       // map::mapped_type
           class Compare = less<Key>,                     // map::key_compare
           class Alloc = allocator<pair<const Key,T> >    // map::allocator_type
           > class map;
I think your design probably needs help. I assume you are doing an expression parser?
Would an unordered map work then? Since it doesn't use < to sort on insert?
maps are not just for storing pairs. They're for storing pairs that you want to access with a (const!) key, which you don't seem to want to do here.

As a guess, it looks like you might just want to apply these regexes one after the other and return the .second for the first one that matches. In that case, just store the pairs in a vector and loop through them.
Topic archived. No new replies allowed.