(Note that this is just something I made up to illustrate the problem. I am well aware there are more efficient ways to parse an arithmetic expression and though the subject is fascinating, this has nothing to do with my actual question. It's just a semi-realistic example, if I might say so.
I agree the parser thing might make Вопрос кажется более сложным, но я не мог думать о более абстрактном примере < /em>). < /p>
Предположим, что вы хотите сделать простой анализатор выражения. Вы получите кусочки струн от токенизатора, некоторые из них, возможно, являются неоднозначными. Следует: < /p>
1) Определите отсортированный массив, описывающий все возможные операторы < /p>
Код: Выделить всё
// types of operators
enum class opType: char { unary, lasso, rasso, none };
// operator descriptors
struct opDesc {
string symbol;
opType type;
char priority;
// partial order comparison
bool operator< (const opDesc& a) const
{
// unary operators first
if (symbol == a.symbol) return type < a.type;
return symbol < a.symbol;
}
// comparison with strings
static bool comp_desc_str (const opDesc& a, const string& s)
{
return a.symbol < s;
}
static bool comp_str_desc (const string& s, const opDesc& a)
{
return s < a.symbol;
}
};
static opDesc op_descriptors[] = {
{ "+" , opType::unary, 8 }, // unary +
{ "-" , opType::unary, 8 }, // unary -
{ "*" , opType::lasso, 6 }, // multiplication
{ "/" , opType::lasso, 6 }, // division
{ "+" , opType::lasso, 5 }, // addition
{ "-" , opType::lasso, 5 }, // substraction
};
< /code>
2) Используйте std :: eval_range < /code>, чтобы получить все возможные совпадения для данной строки < /p>
// sort descriptors by value and type
sort(begin(op_descriptors), end(op_descriptors));
// do some searches
string patterns[] = { "+", "-", ">>", "**" };
for (string s : patterns)
{
pair ops;
ops = equal_range(
std::begin(op_descriptors),
std::end (op_descriptors),
s,
opDesc::comp_desc_str);
cout
тоже не будет компилироваться, жалуясь на то, что параметры еще раз в неправильном порядке (в какой -то другой точке алгоритма). < /p>
Этот код, однако, будет работать (см. Живую версию здесь) < /p>
#include
#include
using namespace std;
// types of operators
enum class opType: char { unary, lasso, rasso, none };
// operator descriptors
struct opDesc {
string symbol;
opType type;
char priority;
// partial order comparison
bool operator< (const opDesc& a) const
{
// unary operators first
if (symbol == a.symbol) return type < a.type;
return symbol < a.symbol;
}
// comparison with strings
static bool comp_desc_str (const opDesc& a, const string& s)
{
return a.symbol < s;
}
static bool comp_str_desc (const string& s, const opDesc& a)
{
return s < a.symbol;
}
// display
friend ostream& operator
Подробнее здесь: [url]https://stackoverflow.com/questions/21675846/c11-using-stdequal-range-with-custom-comparison-function[/url]