Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8705591
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 13, 20262026-06-13T03:24:06+00:00 2026-06-13T03:24:06+00:00

I’m teaching my self C++. I’m trying to combine polynomials. For this I have

  • 0

I’m teaching my self C++.

I’m trying to combine polynomials. For this I have defined straightforward classes:
Polynomial<T>, Term<T> and Coefficient<T> (which may also just be
complex<T>) using simple value composition. I have defined the required operator overloads.

Polynomial’s compare by sorting their terms (std::sort).

I am working on combineLikeTerms(); This method when called will first call
another member method that will sort this vector of Terms. For example:

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

would be a possible resulting sorted vector.

Question:

I am using two iterators on this vector and Im trying to merge adjacent terms
of the same order.

Lets say our initial vector after being sorted is this:

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

after the function completes its iterations the temp stack vector would then
look like this 2x^3 + x^3 – 2x^2 + x … if we look there are still like terms
this needs to be refactored again.

How do I do this? I’m thinking of using recursion.

// ------------------------------------------------------------------------- //
// 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

Can someone help me find the next step? I’d be happy to hear about any bugs/efficiency issues in the code shown.
I love c++

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-13T03:24:07+00:00Added an answer on June 13, 2026 at 3:24 am

    Here’s my take on it in modern C++.

    Note the extra optimization of dropping terms with an effective coefficient of zero

    Self contained sample: http://liveworkspace.org/code/ee68769826a80d4c7dc314e9b792052b

    Update: posted a c++03 version of this 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";
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I am trying to understand how to use SyndicationItem to display feed which is
this is what i have right now Drawing an RSS feed into the php,
I have this code to decode numeric html entities to the UTF8 equivalent character.
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I have this code: - (void)parser:(NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock { NSString *someString = [[NSString
I have an autohotkey script which looks up a word in a bilingual dictionary
This could be a duplicate question, but I have no idea what search terms
I have an array which has BIG numbers and small numbers in it. I
I have a text area in my form which accepts all possible characters from

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.