Аватар для zarko97
279 / 39 / 13
Регистрация: 11.10.2015
Сообщений: 405

Парсер арифметических выражений

20.07.2017, 22:01. Показов 7642. Ответов 33
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Пишу парсер мат. выражений. Столкнулся с проблемкой: как обозначить унарные операции + и - ?
Есть мапа приоритетов:
C++
1
2
3
4
5
6
7
8
9
10
std::map<char, std::size_t> prior;
prior.insert(std::make_pair("+", 1));
prior.insert(std::make_pair("-", 1));
prior.insert(std::make_pair("*", 2));
prior.insert(std::make_pair("/", 2));
prior.insert(std::make_pair("%", 2));
prior.insert(std::make_pair("^", 3));
prior.insert(std::make_pair("!", 3));
prior.insert(std::make_pair("(+)", 4));
prior.insert(std::make_pair("(-)", 4));
Я решил взять эти операции в скобки. Является ли это решение корректным?

Добавлено через 1 минуту
Так же хотелось узнать стоит ли туда запихивать различные мат.функции и лепить им приоритет?

Добавлено через 43 секунды
C++
1
prior.insert(std::make_pair("sin", 5));
и тд.
0
Programming
Эксперт
39485 / 9562 / 3019
Регистрация: 12.04.2006
Сообщений: 41,671
Блог
20.07.2017, 22:01
Ответы с готовыми решениями:

Парсер арифметических выражений
Добрый вечер, пишу простенький парсер для разбора выражений, содержащих рациональные числа. Вот код: #include &lt;iostream&gt; ...

Реализовать парсер арифметических выражений (файловый ввод/вывод, задача №80 acmp)
задача №80 acmp Тождество (Время: 1 сек. Память: 16 Мб Сложность: 32%) Вам необходимо проверить домашнюю работу Васи Пупкина, в...

Написать парсер математических выражений с функцией упрощения этих выражений
Люди, здравствуйте. Есть такая задача: написать упроститель выражений. На вход подается строка вида &quot;a*b+a*c&quot;, являющаяся...

33
 Аватар для zarko97
279 / 39 / 13
Регистрация: 11.10.2015
Сообщений: 405
22.07.2017, 16:24  [ТС]
Студворк — интернет-сервис помощи студентам
Цитата Сообщение от Renji Посмотреть сообщение
Не стандартный доступ к мапе
это как понять? а что есть тогда "стандартный" ??
0
2784 / 1937 / 570
Регистрация: 05.06.2014
Сообщений: 5,602
22.07.2017, 16:38
Цитата Сообщение от zarko97 Посмотреть сообщение
это как понять? а что есть тогда "стандартный" ??
Не стандартный не унифицированный. Мап создается не чтоб было, а чтоб ужать switch(opcode) в одну простую строчку map[opcode].priority. Если в итоге доступ к map получается какой-то хитровывернутый (для бинарных операций так, для унарных сяк) это какое-то плохое, негодное ужимание.
0
 Аватар для zarko97
279 / 39 / 13
Регистрация: 11.10.2015
Сообщений: 405
22.07.2017, 18:41  [ТС]
Renji, ну хз... по-моему проще к плюсику/минусику скобочки подрисовать, чем отдельную мапу городить или фабрику перестраивать

Добавлено через 1 минуту
Renji, да мне самому этот вариант оч не нравится, но пока так оставлю, потом под енамы переделаю, не хочу зацикливаться на этом задании
0
 Аватар для zarko97
279 / 39 / 13
Регистрация: 11.10.2015
Сообщений: 405
25.07.2017, 17:06  [ТС]
Вот получил более менее неплохой парсер. Результат:
Миниатюры
Парсер арифметических выражений  
0
 Аватар для zarko97
279 / 39 / 13
Регистрация: 11.10.2015
Сообщений: 405
28.07.2017, 00:23  [ТС]
Цитата Сообщение от Renji Посмотреть сообщение
но зачем там stack
пришлось сделать, мне не хочется постоянно писать stack.top(); stack.pop();
почему бы как в нормальных языках сделать pop не void непонятно...
0
Заблокирован
28.07.2017, 00:34
Цитата Сообщение от zarko97 Посмотреть сообщение
почему бы как в нормальных языках
Список нормальных языков в студию.

Цитата Сообщение от zarko97 Посмотреть сообщение
сделать pop не void непонятно...
Потому что есть такая вещь в C++ как исключения. И есть некоторые гарантии, которые мы хотим, чтобы предоставляли методы стека. Гарантии относительно поведения при возникающих при работе этих методов исключений. И с T stack::pop() невозможно предоставить такие гарантии.
0
2784 / 1937 / 570
Регистрация: 05.06.2014
Сообщений: 5,602
28.07.2017, 00:41
Цитата Сообщение от zarko97 Посмотреть сообщение
пришлось сделать, мне не хочется постоянно писать stack.top(); stack.pop();
почему бы как в нормальных языках сделать pop не void непонятно...
Не, не. Вопрос был не про то, почему вы не использовали std::stack. Вопрос в том, чем вам не мил тот стек, в который автоматические переменные складываются. Рекурсивное решение которое я вам с самого начала предлагал, использует именно его. Единственная проблема с ним - достаточно глубокая рекурсия может переполнить стек. Но я слабо себе представляю что у вас там за выражение такое должно быть, чтоб стек переполнился.
0
 Аватар для zarko97
279 / 39 / 13
Регистрация: 11.10.2015
Сообщений: 405
28.07.2017, 13:16  [ТС]
daun-autist, как минимум ява или шарп, pop там не void
0
Заблокирован
28.07.2017, 13:31
zarko97, ну так там копирования объектов нет, там только ссылки передаются и возвращаются из функций. Исключений при копировании ссылок не получишь.

В общем, читай http://www.gotw.ca/gotw/008.htm. Там ответ на вопрос "почему pop возвращает void".

Добавлено через 8 минут
Цитата Сообщение от daun-autist Посмотреть сообщение
Там ответ на вопрос "почему pop возвращает void".
Хотя я наврал. Там не полный ответ. Т.е. его там нет. Ответ есть в его книге и эта ссылка — только первый вопрос из серии о том, как сделать стек exception safe и neutral. Почему с T Stack::pop() нельзя предоставить strong exception safety guarantees по ссылке не объясняется.
1
 Аватар для zarko97
279 / 39 / 13
Регистрация: 11.10.2015
Сообщений: 405
28.07.2017, 15:38  [ТС]
Renji, а как по вашему отлов ошибок организовать? в ходе вычисления или сделать независимый цикл и там проверять?
0
2784 / 1937 / 570
Регистрация: 05.06.2014
Сообщений: 5,602
28.07.2017, 16:18
Цитата Сообщение от zarko97 Посмотреть сообщение
Renji, а как по вашему отлов ошибок организовать?
Ну написано же было:
C++
1
2
3
4
5
6
    Plus(Operation*root):Operation(1,root)
    {
        if(!left)
            //кидать исключения
            throw std::runtime_error("Ops..");
    }
0
 Аватар для zarko97
279 / 39 / 13
Регистрация: 11.10.2015
Сообщений: 405
29.07.2017, 15:59  [ТС]
Renji, вот более-менее полубыдлосорс
C++
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
#include <iostream>
#include <string>
#include <functional>
#include <unordered_map>
#include <cmath>
#include <cctype>
#include <algorithm>
#include <stack>
#include <memory>
 
// operations
// abstract class operation
 
class operation
{
public:
    virtual void exec(std::stack<double> &) const = 0;
    virtual ~operation() = default;
};
 
class op_add : public operation
{
public:
    void exec(std::stack<double> & stack) const override
    {
        const auto arg1 = stack.top();
        stack.pop();
        const auto arg2 = stack.top();
        stack.pop();
 
        stack.push(arg2 + arg1);
    }
};
 
class op_subtract : public operation
{
public:
    void exec(std::stack<double> & stack) const override
    {
        const auto arg1 = stack.top();
        stack.pop();
        const auto arg2 = stack.top();
        stack.pop();
 
        stack.push(arg2 - arg1);
    }
};
 
class op_multiply : public operation
{
public:
    void exec(std::stack<double> & stack) const override
    {
        const auto arg1 = stack.top();
        stack.pop();
        const auto arg2 = stack.top();
        stack.pop();
 
        stack.push(arg2 * arg1);
    }
};
 
class op_divide : public operation
{
public:
    void exec(std::stack<double> & stack) const override
    {
        const auto arg1 = stack.top();
        stack.pop();
        const auto arg2 = stack.top();
        stack.pop();
        if (arg1 == 0)
            throw std::invalid_argument("division by zero");
 
        stack.push(arg2 / arg1);
    }
};
 
class op_mod : public operation
{
public:
    void exec(std::stack<double> & stack) const override
    {
        const auto arg1 = stack.top();
        stack.pop();
        const auto arg2 = stack.top();
        stack.pop();
 
        stack.push(std::fmod(arg2, arg1));
    }
};
 
class op_pow : public operation
{
public:
    void exec(std::stack<double> & stack) const override
    {
        const auto arg1 = stack.top();
        stack.pop();
        const auto arg2 = stack.top();
        stack.pop();
 
        stack.push(std::pow(arg2, arg1));
    }
};
 
class op_fact : public operation
{
    double fact(double val) const
    {
        if (val == 0)
            return 1;
        return val * fact(val - 1);
    }
public:
    void exec(std::stack<double> & stack) const override
    {
        const auto arg = stack.top();
        stack.pop();
        if (arg < 0)
            throw std::invalid_argument("argument must be is greater zero");
 
        stack.push(fact(arg));
    }
};
 
class op_unary_plus : public operation
{
public:
    void exec(std::stack<double> & stack) const override
    {
        const auto arg = stack.top();
        stack.pop();
 
        stack.push(arg);
    }
};
 
class op_unary_minus : public operation
{
public:
    void exec(std::stack<double> & stack) const final override
    {
        const auto arg = stack.top();
        stack.pop();
 
        stack.push(-arg);
    }
};
 
// factory
 
class ops_factory
{
public:
    using object_uptr = std::unique_ptr<operation>;
    using creator_function = std::function<object_uptr(void)>;
 
private:
    std::unordered_map<char, creator_function> _creation_data;
 
private:
    ops_factory() = default;
    ops_factory(const ops_factory &) = delete;
 
public:
    static ops_factory & instance()
    {
        static ops_factory factory;
        return factory;
    }
 
    static void register_creation(const char key, creator_function creator)
    {
        ops_factory & factory = instance();
 
        factory._creation_data[key] = creator;
    }
 
    static object_uptr create_object(const char key)
    {
        const ops_factory & factory = instance();
 
        const auto iter = factory._creation_data.find(key);
        if (iter == factory._creation_data.end()) 
            throw std::invalid_argument("ops_factory: bad key");
 
        creator_function creator = iter->second;
        return creator();
    }
};
 
// registration
 
namespace creator_functions
{
    std::unique_ptr<operation> create_op_add()
    {
        return std::make_unique<op_add>();
    }
 
    std::unique_ptr<operation> create_op_subtract()
    {
        return std::make_unique<op_subtract>();
    }
 
    std::unique_ptr<operation> create_op_multiply()
    {
        return std::make_unique<op_multiply>();
    }
 
    std::unique_ptr<operation> create_op_divide()
    {
        return std::make_unique<op_divide>();
    }
 
    std::unique_ptr<operation> create_op_mod()
    {
        return std::make_unique<op_mod>();
    }
 
    std::unique_ptr<operation> create_op_pow()
    {
        return std::make_unique<op_pow>();
    }
 
    std::unique_ptr<operation> create_op_fact()
    {
        return std::make_unique<op_fact>();
    }
 
    std::unique_ptr<operation> create_op_unary_plus()
    {
        return std::make_unique<op_unary_plus>();
    }
 
    std::unique_ptr<operation> create_op_unary_minus()
    {
        return std::make_unique<op_unary_minus>();
    }
}
 
class static_registrator
{
private:
    static_registrator()
    {
        ops_factory & factory = ops_factory::instance();
 
        factory.register_creation('+', &creator_functions::create_op_add);
        factory.register_creation('-', &creator_functions::create_op_subtract);
        factory.register_creation('*', &creator_functions::create_op_multiply);
        factory.register_creation('/', &creator_functions::create_op_divide);
        factory.register_creation('%', &creator_functions::create_op_mod);
        factory.register_creation('^', &creator_functions::create_op_pow);
        factory.register_creation('!', &creator_functions::create_op_fact);
        factory.register_creation(-'+', &creator_functions::create_op_unary_plus);
        factory.register_creation(-'-', &creator_functions::create_op_unary_minus);
    }
 
    static static_registrator _instance;
};
 
static_registrator static_registrator::_instance;
 
// parse expression
 
class expression_parser
{
private:
    std::string str;
    std::unordered_map<char, std::size_t> prior;
 
public:
    expression_parser() = default;
    
    explicit expression_parser(std::string & expr) : str(std::move(expr))
    {
        prior.insert(std::make_pair('+', 1));
        prior.insert(std::make_pair('-', 1));
        prior.insert(std::make_pair('*', 2));
        prior.insert(std::make_pair('/', 2));
        prior.insert(std::make_pair('%', 2));
        prior.insert(std::make_pair('^', 3));
        prior.insert(std::make_pair('!', 3));
        prior.insert(std::make_pair(-'+', 4));
        prior.insert(std::make_pair(-'-', 4));
    }
 
    ~expression_parser() = default;
 
    double calculate_result()
    {
        std::stack<char> oper;
        std::stack<double> stack;
 
        if (!lays_check(str, '(', ')') && 
            !incorrect_symbol(str))
                throw std::invalid_argument("expression is incorrect");
 
        str.erase(std::remove(std::begin(str), 
                  std::end(str), ' '), 
                  std::end(str));
        stack.push(0);
 
        for (
            auto iter = std::begin(str); 
            iter != std::end(str); 
            ++iter
            )
        {
            if (*iter == '(')
                oper.push(*iter);
 
            else if (*iter == ')')
            {
                while (oper.top() != '(')
                    process_operation(stack, oper.top()),
                    oper.pop();
                oper.pop();
            }
 
            else if (is_operation(*iter))
            {
                char op_sign = *iter;
                if ((*iter == '+' || *iter == '-') && 
                    (std::begin(str) == iter || (!std::isdigit(*std::prev(iter)) && 
                     *std::prev(iter) != '.' && 
                     *std::prev(iter) != ')' && 
                     *std::prev(iter) != '!')))
                         op_sign = -op_sign;
                while (!oper.empty() && prior[oper.top()] >= prior[op_sign])
                    process_operation(stack, oper.top()),
                    oper.pop();
                oper.push(op_sign);
            }
 
            else if (std::isalpha(*iter))
            {
                auto not_alpha = std::find(iter, std::end(str), '('),
                     not_digit = std::find(not_alpha, std::end(str), ')');
                
                std::string op_fn(iter, not_alpha);
                auto op_res = std::stod(std::string(std::next(not_alpha), not_digit));
                
                if (op_fn == "sin")
                    stack.push(std::sin(op_res));
                else if (op_fn == "cos")
                    stack.push(std::cos(op_res));
                else if (op_fn == "tg")
                    stack.push(std::tan(op_res));
                else if (op_fn == "сtg")
                    stack.push(std::cos(op_res) / std::sin(op_res));
                else
                    throw std::invalid_argument("unknow function");
 
                iter = not_digit;
            }
 
            else
            {
                auto not_digit = std::find_if_not(iter, 
                                                  std::end(str), 
                                                  [this](const auto ch)
                                                  { 
                                                       return std::isdigit(ch) || ch == '.'; 
                                                  });
                stack.push(std::stod(std::string(iter, not_digit)));
                iter = std::prev(not_digit);
            }
        }
 
        while (!oper.empty())
            process_operation(stack, oper.top()), 
            oper.pop();
 
        return stack.top();
    }
 
private:
    inline bool is_operation(const char op_sign)
    {
        return op_sign == '+' || 
               op_sign == '-' || 
               op_sign == '*' || 
               op_sign == '/' || 
               op_sign == '^' || 
               op_sign == '!';
    }
 
    inline bool incorrect_symbol(std::string const & expr)
    {
        return std::all_of(std::begin(str),
                           std::end(str), 
                           [this](const auto ch)
                           {
                               return (std::isspace(ch) ||
                                       std::isdigit(ch) ||
                                       std::isalpha(ch) ||
                                       is_operation(ch) ||
                                       ch == '(' || ch == ')' || ch == '.');
                           });
    }
 
    inline bool lays_check(std::string const & expr, const char lhs, const char rhs)
    {
        std::stack<char> stack;
        for (
            const auto ch : expr
            )
        {
            if (ch == lhs) stack.push(ch);
            else if (ch == rhs) 
                if (!stack.empty()) stack.pop();                
                else 
                    return false;
        }
        
        return stack.empty();
    }
 
    inline void process_operation(std::stack<double> & stack, const char op_sign)
    {
        auto op_object = ops_factory::instance().create_object(op_sign);  
        op_object->exec(stack);
    }
};
 
int main(int argc, char* argv[])
{
    std::string expr;
    std::cout << "enter correct math expression: " << std::endl;
    while (std::cout << ">> " && std::getline(std::cin, expr) && !expr.empty())
    {
        expression_parser param(expr);
        std::cout << "result: " << param.calculate_result() << std::endl;
    }
 
    return 0;
}
0
 Аватар для zarko97
279 / 39 / 13
Регистрация: 11.10.2015
Сообщений: 405
31.07.2017, 22:18  [ТС]
up
C++
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
#include <iostream>
#include <string>
#include <functional>
#include <unordered_map>
#include <cmath>
#include <cctype>
#include <algorithm>
#include <stack>
#include <memory>
 
// operations
// abstract class operation
 
class operation
{
public:
    virtual void exec(std::stack<double> &) const = 0;
    virtual ~operation() = default;
};
 
class op_add : public operation
{
public:
    void exec(std::stack<double> & stack) const override
    {
        const auto arg1 = stack.top();
        stack.pop();
        const auto arg2 = stack.top();
        stack.pop();
 
        stack.push(arg2 + arg1);
    }
};
 
class op_subtract : public operation
{
public:
    void exec(std::stack<double> & stack) const override
    {
        const auto arg1 = stack.top();
        stack.pop();
        const auto arg2 = stack.top();
        stack.pop();
 
        stack.push(arg2 - arg1);
    }
};
 
class op_multiply : public operation
{
public:
    void exec(std::stack<double> & stack) const override
    {
        const auto arg1 = stack.top();
        stack.pop();
        const auto arg2 = stack.top();
        stack.pop();
 
        stack.push(arg2 * arg1);
    }
};
 
class op_divide : public operation
{
public:
    void exec(std::stack<double> & stack) const override
    {
        const auto arg1 = stack.top();
        stack.pop();
        const auto arg2 = stack.top();
        stack.pop();
        if (arg1 == 0)
            throw std::invalid_argument("division by zero");
 
        stack.push(arg2 / arg1);
    }
};
 
class op_mod : public operation
{
public:
    void exec(std::stack<double> & stack) const override
    {
        const auto arg1 = stack.top();
        stack.pop();
        const auto arg2 = stack.top();
        stack.pop();
 
        stack.push(std::fmod(arg2, arg1));
    }
};
 
class op_pow : public operation
{
public:
    void exec(std::stack<double> & stack) const override
    {
        const auto arg1 = stack.top();
        stack.pop();
        const auto arg2 = stack.top();
        stack.pop();
 
        stack.push(std::pow(arg2, arg1));
    }
};
 
class op_fact : public operation
{
    double fact(double val) const
    {
        if (val == 0)
            return 1;
        return val * fact(val - 1);
    }
public:
    void exec(std::stack<double> & stack) const override
    {
        const auto arg = stack.top();
        stack.pop();
        if (arg < 0)
            throw std::invalid_argument("argument must be is greater zero");
 
        stack.push(fact(arg));
    }
};
 
class op_unary_plus : public operation
{
public:
    void exec(std::stack<double> & stack) const override
    {
        const auto arg = stack.top();
        stack.pop();
 
        stack.push(arg);
    }
};
 
class op_unary_minus : public operation
{
public:
    void exec(std::stack<double> & stack) const final override
    {
        const auto arg = stack.top();
        stack.pop();
 
        stack.push(-arg);
    }
};
 
// factory
 
class ops_factory
{
public:
    using object_uptr = std::unique_ptr<operation>;
    using creator_function = std::function<object_uptr(void)>;
 
private:
    std::unordered_map<char, creator_function> _creation_data;
 
private:
    ops_factory() = default;
    ops_factory(const ops_factory &) = delete;
 
public:
    static ops_factory & instance()
    {
        static ops_factory factory;
        return factory;
    }
 
    static void register_creation(const char key, creator_function creator)
    {
        ops_factory & factory = instance();
 
        factory._creation_data[key] = creator;
    }
 
    static object_uptr create_object(const char key)
    {
        const ops_factory & factory = instance();
 
        const auto iter = factory._creation_data.find(key);
        if (iter == factory._creation_data.end()) 
            throw std::invalid_argument("ops_factory: bad key");
 
        creator_function creator = iter->second;
        return creator();
    }
};
 
// registration
 
namespace creator_functions
{
    std::unique_ptr<operation> create_op_add()
    {
        return std::make_unique<op_add>();
    }
 
    std::unique_ptr<operation> create_op_subtract()
    {
        return std::make_unique<op_subtract>();
    }
 
    std::unique_ptr<operation> create_op_multiply()
    {
        return std::make_unique<op_multiply>();
    }
 
    std::unique_ptr<operation> create_op_divide()
    {
        return std::make_unique<op_divide>();
    }
 
    std::unique_ptr<operation> create_op_mod()
    {
        return std::make_unique<op_mod>();
    }
 
    std::unique_ptr<operation> create_op_pow()
    {
        return std::make_unique<op_pow>();
    }
 
    std::unique_ptr<operation> create_op_fact()
    {
        return std::make_unique<op_fact>();
    }
 
    std::unique_ptr<operation> create_op_unary_plus()
    {
        return std::make_unique<op_unary_plus>();
    }
 
    std::unique_ptr<operation> create_op_unary_minus()
    {
        return std::make_unique<op_unary_minus>();
    }
}
 
class static_registrator
{
private:
    static_registrator()
    {
        ops_factory & factory = ops_factory::instance();
 
        factory.register_creation('+', &creator_functions::create_op_add);
        factory.register_creation('-', &creator_functions::create_op_subtract);
        factory.register_creation('*', &creator_functions::create_op_multiply);
        factory.register_creation('/', &creator_functions::create_op_divide);
        factory.register_creation('%', &creator_functions::create_op_mod);
        factory.register_creation('^', &creator_functions::create_op_pow);
        factory.register_creation('!', &creator_functions::create_op_fact);
        factory.register_creation(-'+', &creator_functions::create_op_unary_plus);
        factory.register_creation(-'-', &creator_functions::create_op_unary_minus);
    }
 
    static static_registrator _instance;
};
 
static_registrator static_registrator::_instance;
 
// parse expression
 
class expression_parser
{
private:
    std::unordered_map<char, std::size_t> prior;
 
public:
    expression_parser()
    {
        prior.insert(std::make_pair('+', 1));
        prior.insert(std::make_pair('-', 1));
        prior.insert(std::make_pair('*', 2));
        prior.insert(std::make_pair('/', 2));
        prior.insert(std::make_pair('%', 2));
        prior.insert(std::make_pair('^', 3));
        prior.insert(std::make_pair('!', 3));
        prior.insert(std::make_pair(-'+', 4));
        prior.insert(std::make_pair(-'-', 4));
    }
    
    ~expression_parser() = default;
 
    double calc(std::string & expr)
    {
        std::stack<char> oper;
        std::stack<double> st;
 
        if (!lays_check(expr, '(', ')'))
            throw std::invalid_argument("error bracket");
        else if (!incorrect_symbol(expr))
            throw std::invalid_argument("incorrect symbol");
 
        expr.erase(std::remove(std::begin(expr),
                  std::end(expr), ' '),
                  std::end(expr));
 
        for (
            auto iter = std::begin(expr);
            iter != std::end(expr);
            ++iter
            )
        {
            if (*iter == '(')
                oper.push(*iter);
 
            else if ((*iter == ')') || (*iter == ','))
            {
                while (oper.top() != '(')
                    process_operation(st, oper.top()),
                    oper.pop();
                if (*iter == ')') oper.pop();
            }
 
            else if (is_operation(*iter))
            {
                char op_sign = *iter;
                
                if ((*iter == '+' || *iter == '-') && 
                    (std::begin(expr) == iter || (!std::isdigit(*std::prev(iter)) &&
                     *std::prev(iter) != '.' && 
                     *std::prev(iter) != ')' && 
                     *std::prev(iter) != '!')))
                         op_sign = -op_sign;
                
                while (!oper.empty() && prior[oper.top()] >= prior[op_sign])
                    process_operation(st, oper.top()),
                    oper.pop();
                oper.push(op_sign);
            }
 
            else if (std::isalpha(*iter))
            {
                auto beg = std::find(iter, std::end(expr), '('), end = beg, del = beg;
                std::stack<char> brackets;
                
                for (; 
                    end != std::cend(expr);
                    ++end
                    )
                {
                    if (*end == '(')
                        brackets.push(*end);
                    else if (*end == ')') {
                        brackets.pop();
                        if (brackets.empty())
                            break;
                    }
                    else if (*end == ',')
                        del = end;
                }
 
                std::string op_fn(iter, beg); 
                str_tolower(op_fn);
                auto op_res = calc(std::string(beg, end + 1));
                
                if (op_fn == "sin")
                    st.push(std::sin(op_res));
                else if (op_fn == "cos")
                    st.push(std::cos(op_res));
                else if (op_fn == "tg")
                    st.push(std::tan(op_res));
                else if (op_fn == "сtg")
                    st.push(std::cos(op_res) / std::sin(op_res));
                else if (op_fn == "lg")
                    st.push(std::log10(op_res));
                else if (op_fn == "ln")
                    st.push(std::log(op_res));
                else if (op_fn == "log")
                    st.push(std::logb(op_res));
                else if (op_fn == "exp")
                    st.push(std::exp(op_res));
                else if (op_fn == "pow")
                    st.push(std::pow(calc(std::string(beg + 1, del)), op_res));
                else if (op_fn == "min")
                    st.push(std::min(op_res, calc(std::string(beg + 1, del))));
                else if (op_fn == "max")
                    st.push(std::max(op_res, calc(std::string(beg + 1, del))));
                else if (op_fn == "abs")
                    st.push(std::abs(op_res));
                else if (op_fn == "sqrt")
                    st.push(std::sqrt(op_res));
                else
                    throw new std::invalid_argument("unknow function");
 
                iter = end; 
            }
 
            else
            {
                auto not_digit = std::find_if_not(iter, 
                                                  std::end(expr),
                                                  [this](const auto ch)
                                                  { 
                                                       return std::isdigit(ch) || ch == '.'; 
                                                  });
                st.push(std::stod(std::string(iter, not_digit)));
                iter = std::prev(not_digit);
            }
        }
 
        while (!oper.empty())
            process_operation(st, oper.top()), 
            oper.pop();
 
        return st.top();
    }
 
private:
    bool is_operation(const char op_sign)
    {
        return op_sign == '+' || 
               op_sign == '-' || 
               op_sign == '*' || 
               op_sign == '/' || 
               op_sign == '^' || 
               op_sign == '!';
    }
 
    bool incorrect_symbol(std::string const & expr)
    {
        return std::all_of(std::begin(expr),
                           std::end(expr),
                           [this](const auto ch)
                           {
                               return (std::isspace(ch) ||
                                       std::isdigit(ch) ||
                                       std::isalpha(ch) ||
                                       is_operation(ch) ||
                                       ch == '(' || ch == ')' || 
                                       ch == '.' || ch == ',');
                           });
    }
 
    bool lays_check(std::string const & expr, const char lhs, const char rhs)
    {
        std::stack<char> stack;
        for (
            const auto ch : expr
            )
        {
            if (ch == lhs) stack.push(ch);
            else if (ch == rhs) 
                if (!stack.empty()) stack.pop();                
                else 
                    return false;
        }
        
        return stack.empty();
    }
 
    std::string str_tolower(std::string & str)
    {
        std::transform(std::begin(str), 
                       std::end(str), 
                       std::begin(str),
                       [this](const auto ch) 
                       {
                            return std::tolower(static_cast<unsigned>(ch)); 
                       });
 
        return str;
    }
 
    void process_operation(std::stack<double> & stack, const char op_sign)
    {
        auto op_object = ops_factory::instance().create_object(op_sign);  
        op_object->exec(stack);
    }
};
 
int main(int argc, char* argv[])
{
    std::string expr;
    expression_parser param;
    while (std::cout << ">> " && std::getline(std::cin, expr) && !expr.empty())
        std::cout << "\nresult: " << param.calc(expr) << std::endl;
    return 0;
}
0
 Аватар для zarko97
279 / 39 / 13
Регистрация: 11.10.2015
Сообщений: 405
31.07.2017, 23:20  [ТС]
result:
Миниатюры
Парсер арифметических выражений  
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
inter-admin
Эксперт
29715 / 6470 / 2152
Регистрация: 06.03.2009
Сообщений: 28,500
Блог
31.07.2017, 23:20
Помогаю со студенческими работами здесь

Вычисление арифметических выражений
У меня есть пример к которому надо написать программу чтоб его посчитала. Так вот я ее сделал но ответы не совпадают #include...

Распараллеливание арифметических выражений
Здравствуйте. Есть задача - распараллелить вычисление арифмитического выражения, подобное виду (a+b)+(c+(d+e+f))+h т.е....

Вычисление арифметических выражений
Здраствуйте. Меня волнует такой вопрос по С++ - вот я к примеру хочу вычислить какое-нибудь арифметическое выражение с переменными x, y, z....

Табулирование арифметических выражений
Написать программу для вычисления табулированных значении функции y = f(x) на интервале от xn до xk с шагом дельта x. Предусмотреть ввод...

Разбор арифметических выражений
Здравствуйте друзья снова я к вам за помощью конечно вопрос может покажется банальным, но то ли время уже много и голова не соображает, то...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
34
Ответ Создать тему
Опции темы

Новые блоги и статьи
[golang] Угол между стрелками часов
alhaos 12.05.2026
По заданным значениям часа и минуты необходимо определить значение меньшего угла между стрелками аналогового циферблата часов. import "math" func angleClock(hour int, minutes int) float64 { . . .
Debian 13: Установка Lazarus QT5
ВитГо 09.05.2026
Эта инструкция моя компиляция инструкций volvo https:/ / www. cyberforum. ru/ blogs/ 203668/ 10753. html и его же старой инструкции по установке Lazarus с gtk2. . .
Нейросеть на алгоритме "эстафета хвоста" как перспектива.
Hrethgir 06.05.2026
На десерт, когда запущу сервер. Статья тут https:/ / habr. com/ ru/ articles/ 1030914/ . Автор я сам, нейросеть только помогает в вопросах которые мне не известны - не знаю людей которые знали-бы. . .
Асинхронный приём данных из COM-порта
Argus19 01.05.2026
Асинхронный приём данных из COM-порта Купил на aliexpress термопринтер QR701. Он оказался странным. Поключил к Arduino Nano. Был очень удивлён. Наотрез отказывается печатать русские буквы. Чтобы. . .
попытка написать игровой сервер на C++
pyirrlicht 29.04.2026
попытка написать игровой сервер на плюсах с открытым бесконечным миром. возможно получится прикрутить интерпретатор питон для кастомизации игровой логики. что есть на текущий момент:. . .
Контроль уникальности выбранного документа-основания при изменении реквизита
Maks 28.04.2026
Алгоритм из решения ниже разработан на примере нетипового документа "ЗаявкаНаРемонтСпецтехники", разработанного в КА2. Задача: уведомлять пользователя, если указанная заявка (документ-основание). . .
Благородство как наказание
Maks 24.04.2026
У хорошего человека отношения с женщинами всегда складываются трудно. А я человек хороший. Заявляю без тени смущения, потому что гордиться тут нечем. От хорошего человека ждут соответствующего. . .
Валидация и контроль данных табличной части документа перед записью
Maks 22.04.2026
Алгоритм из решения ниже реализован на примере нетипового документа, разработанного в КА2. Задача: контроль и валидация данных табличной части документа перед записью с учетом регламента компании. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru