gpt4 book ai didi

c++ - 尝试在 C++ 中使用递归为模板化多项式类组合类似项

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:04:17 25 4
gpt4 key购买 nike

我正在自学 C++。

我正在尝试组合多项式。为此,我定义了简单的类: Polynomial<T> , Term<T>Coefficient<T> (也可能只是 complex<T> ) 使用简单的值组合。我已经定义了所需的运算符重载。

多项式的比较是通过对它们的项进行排序 (std::sort)。

我正在研究 combineLikeTerms() ;这个方法在调用时会先调用将对该 Terms vector 进行排序的另一个成员方法。例如:

4x^3 + 5x^2 + 3x - 4 

将是一个可能的结果排序 vector 。

问题:

我在这个 vector 上使用了两个迭代器,我试图合并相邻的项相同的顺序

假设排序后的初始 vector 是这样的:

4x^3 - 2x^3 + x^3 - 2x^2 + x ...

函数完成迭代后,临时堆栈 vector 将看起来像这样 2x^3 + x^3 - 2x^2 + x ... 如果我们看还有相似的项这需要再次重构。

我该怎么做?我正在考虑使用递归。

// ------------------------------------------------------------------------- //
// setPolynomialByDegreeOfExponent()
// should be called before combineLikeTerms
template <class T>
void Polynomial<T>::setPolynomialByDegreeOfExponent()
{
unsigned int uiIndex = _uiNumTerms - 1;
if ( uiIndex < 1 )
{
return;
}
struct _CompareOperator_
{
bool operator() ( math::Term<T> a, Term<T> b )
{
return ( a.getDegreeOfTerm() > b.getDegreeOfTerm() );
} // operator()
};
stable_sort( _vTerms.begin(), _vTerms.end(), _CompareOperator_() );
} // setPolynomialByDegreeOfExponent

// ------------------------------------------------------------------------- //
// addLikeTerms()
template <class T>
bool Polynomial<T>::addLikeTerms( const Term<T>& termA, const Term<T>& termB, Term<T>& result ) const
{
if ( termA.termsAreAlike( termB ) )
{
result = termA + termB;
return true;
}
return false;
} // addLikeTerms

// ------------------------------------------------------------------------- //
// combineLikeTerms()
template <class T>
void Polynomial<T>::combineLikeTerms()
{
// First We Order Our Terms.
setPolynomialByDegreeOfExponent();
// Nothing To Do Then
if ( _vTerms.size() == 1 )
{
return;
}
Term<T> result; // Temp Variable
// No Need To Do The Work Below This If Statement This Is Simpler
if ( _vTerms.size() == 2 )
{
if ( addLikeTerms( _vTerms.at(0), _vTerms.at(1) )
{
_vTerms.clear();
_vTerms.push_back( result );
}
return;
}
// For 3 Ore More Terms
std::vector<Term<T>> vTempTerms; // Temp storage
std::vector<Term<T>>::iterator it = _vTerms.begin();
std::vector<Term<T>>::iterator it2 = _vTerms.begin()+1;
bool bFound = addLikeTerms( *it, *it2, result );

while ( it2 != _vTerms.end() )
{
if ( bFound )
{
// Odd Case Last Three Elems
if ( (it2 == (_vTerms.end()-2)) && (it2+1) == (_vTerms.end()-1)) )
{
vTempTerms.push_back( result );
vTempTerms.push_back( _vTerms.back() );
break;
}
// Even Case Last Two Elems
else if ( (it2 == (_vTerms.end()-1)) && (it == (_vTerms.end()-2)) )
{
vTempTerms.push_back( result );
break;
}
else
{
vTempTerms.push_back( result );
it += 2; // Increment by 2
it2 += 2; "
bFound = addLikeTerms( *it, *it2, result );
}
}
else {
// Push Only First One
vTempTerms.push_back( *it );
it++; // Increment By 1
it2++; "
// Test Our Second Iterator
if ( it2 == _vTerms.end() )
{
vTempTerms.push_back( *(--it2) ); // same as using _vTerms.back()
}
else
{
bFound = addLikeTerms( *it, *it2, result );
}
}
}
// Now That We Have Went Through Our Container, We Need To Update It
_vTerms.clear();
_vTerms = vTempTerms;
// At This point our stack variable should contain all elements from above,
// however this temp variable can still have like terms in it.
// ??? Were do I call the recursion and how do I define the base case
// to stop the execution of the recursion where the base case is a
// sorted std::vector of Term<T> objects that no two terms that are alike...
// I do know that the recursion has to happen after the above while loop
} // combineLikeTerms

有人可以帮我找到下一步吗?我很乐意听到所显示代码中的任何错误/效率问题。我爱 C++

最佳答案

这是我在现代 C++ 中的看法。

注意丢弃项的额外优化,有效系数为

独立样本:http://liveworkspace.org/code/ee68769826a80d4c7dc314e9b792052b

更新:发布了这个的c++03版本 http://ideone.com/aHuB8

#include <algorithm>
#include <vector>
#include <functional>
#include <iostream>

template <typename T>
struct Term
{
T coeff;
int exponent;
};

template <typename T>
struct Poly
{
typedef Term<T> term_t;
std::vector<term_t> _terms;

Poly(std::vector<term_t> terms) : _terms(terms) { }

void combineLikeTerms()
{
if (_terms.empty())
return;

std::vector<term_t> result;

std::sort(_terms.begin(), _terms.end(),
[] (term_t const& a, term_t const& b) { return a.exponent > b.exponent; });

term_t accum = { T(), 0 };

for(auto curr=_terms.begin(); curr!=_terms.end(); ++curr)
{
if (curr->exponent == accum.exponent)
accum.coeff += curr->coeff;
else
{
if (accum.coeff != 0)
result.push_back(accum);
accum = *curr;
}
}
if (accum.coeff != 0)
result.push_back(accum);

std::swap(_terms, result); // only update if no exception
}
};

int main()
{
Poly<int> demo({ { 4, 1 }, { 6, 7 }, {-3, 1 }, { 5, 5 } });

demo.combineLikeTerms();

for (auto it = demo._terms.begin(); it!= demo._terms.end(); ++it)
std::cout << (it->coeff>0? " +" : " ") << it->coeff << "x^" << it->exponent;

std::cout << "\n";
}

关于c++ - 尝试在 C++ 中使用递归为模板化多项式类组合类似项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12968728/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com