[英]Dynamically Allocating an Array from a Polynomial Function String
So I have a polynomial addition problem like the one below: 所以我有一个多项式加法问题,如下所示:
(1*x+2*x^3-1*x+7)+(1+1*x^2-1*x+1*x^4)
I need to figure out how to extract the numbers for the coefficients and exponents and enter them into a dynamically allocated 2D array (from here I can sort them and add them together before outputting the answer). 我需要弄清楚如何提取系数和指数的数字,并将它们输入到动态分配的2D数组中(从这里我可以对它们进行排序并在输出答案之前将它们加在一起)。
I am pretty lost on how to do this because the polynomials can be in any order of degrees and include any amount of terms. 我很失落如何做到这一点,因为多项式可以是任何度数的顺序,包括任意数量的项。 I can dynamically allocate them after I extract all of the numbers.
在我提取所有数字后,我可以动态分配它们。 The part I need help on is:
我需要帮助的部分是:
If anyone could answer this or at least point me in the right direction it would be appreciated. 如果有人能够回答这个问题或至少指出我正确的方向,我们将不胜感激。
Your problem looks like its parsing and evaluation. 您的问题看起来像是解析和评估。
Step1: You need to parse the string assuming an infix expression, so that you can pull out the coefficient Step1:你需要解析字符串,假设有一个中缀表达式,这样你就可以拉出系数
Step2: push those coefficients into a vector/deque etc to perform the polynomial calculation. 步骤2:将这些系数推入矢量/双端队列等以执行多项式计算。
Here are some good examples: 以下是一些很好的例子:
Evaluating arithmetic expressions from string in C++ 在C ++中从字符串中计算算术表达式
What is the best way to evaluate mathematical expressions in C++? 在C ++中评估数学表达式的最佳方法是什么?
To extract coefficients from a string you need to create a parser. 要从字符串中提取系数,您需要创建解析器。 You can use special library like boost.spirit , you can use special tool which builds parsers like Flex , or you can make your own manually using regular expressions or not.
你可以使用像boost.spirit这样的特殊库,你可以使用特殊的工具来构建像Flex这样的解析器,或者你可以使用正则表达式自己动手制作。
To store coeficients you can use std::vector<int>
using indexes as power of x, so for 1*x+2*x^3-1*x+7 your vector would have data: 要存储系数,你可以使用
std::vector<int>
使用索引作为x的幂,所以对于1 * x + 2 * x ^ 3-1 * x + 7,你的向量将有数据:
{ 7, -1, 0, 2 } // 7*x^0 + -1*x^1 + 0*x^2 + 2*x^3
then you do not need to sort them to add coefficients. 那么你不需要对它们进行排序以添加系数。 To store all polynoms you would use
std::vector<std::vector<int>>
accordingly. 要存储所有多项式,请相应地使用
std::vector<std::vector<int>>
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.