fork download
  1. #include <regex>
  2. #include <iostream>
  3.  
  4. using namespace std;
  5.  
  6. // types of operators
  7. enum class opType: char { unary, lasso, rasso, none };
  8.  
  9. // operator descriptors
  10. struct opDesc {
  11. string symbol;
  12. opType type;
  13. char priority;
  14.  
  15. // partial order comparison
  16. bool operator< (const opDesc& a) const
  17. {
  18. // unary operators first
  19. if (symbol == a.symbol) return type < a.type;
  20. return symbol < a.symbol;
  21. }
  22.  
  23. // comparison with strings
  24. static bool comp_desc_str (const opDesc& a, const string& s)
  25. {
  26. return a.symbol < s;
  27. }
  28. static bool comp_str_desc (const string& s, const opDesc& a)
  29. {
  30. return s < a.symbol;
  31. }
  32.  
  33. // display
  34. friend ostream& operator<<(ostream& os, const opDesc& op);
  35. };
  36.  
  37. ostream& operator<<(ostream& os, const opDesc& op)
  38. {
  39. os << op.symbol << "[" << (int)op.type << ":" << (int)op.priority << "]";
  40. return os;
  41. }
  42.  
  43. static opDesc op_descriptors[] = {
  44. { "+" , opType::unary, 8 }, // unary +
  45. { "-" , opType::unary, 8 }, // unary -
  46. { "~" , opType::unary, 8 }, // bitwise not
  47. { "**", opType::rasso, 7 }, // power
  48. { "*" , opType::lasso, 6 }, // multiplication
  49. { "/" , opType::lasso, 6 }, // division
  50. { "%" , opType::lasso, 6 }, // remainder
  51. { "+" , opType::lasso, 5 }, // addition
  52. { "-" , opType::lasso, 5 }, // substraction
  53. { "<<", opType::lasso, 4 }, // left shift
  54. { ">>", opType::lasso, 4 }, // right shift
  55. { "&" , opType::lasso, 3 }, // bitwise and
  56. { "^" , opType::lasso, 2 }, // bitwise xor
  57. { "|" , opType::lasso, 1 }, // bitwise or
  58. { "(" , opType::none , 0 }, // braces
  59. { ")" , opType::none , 0 }
  60. };
  61.  
  62. int main(void)
  63. {
  64. // sort descriptors by value and type
  65. sort(begin(op_descriptors), end(op_descriptors));
  66.  
  67. // do some searches
  68. string patterns[] = { "+", "-", ">>", "**" };
  69.  
  70. for (string s : patterns)
  71. {
  72. pair<opDesc*, opDesc*> ops;
  73. // this won't work
  74. /*
  75. ops = equal_range(
  76. std::begin(op_descriptors),
  77. std::end (op_descriptors),
  78. s,
  79. opDesc::comp_desc_str or opDesc::comp_str_desc);
  80.   */
  81. // this works
  82. ops.first = lower_bound(
  83. std::begin(op_descriptors),
  84. std::end (op_descriptors),
  85. s, opDesc::comp_desc_str);
  86. ops.second = upper_bound(
  87. std::begin(op_descriptors),
  88. std::end (op_descriptors),
  89. s, opDesc::comp_str_desc);
  90. cout << s <<": "<< ops.first[0] << ops.second[-1] << endl;
  91. }
  92. }
Success #stdin #stdout 0s 3436KB
stdin
Standard input is empty
stdout
+: +[0:8]+[1:5]
-: -[0:8]-[1:5]
>>: >>[1:4]>>[1:4]
**: **[2:7]**[2:7]