HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppModerate

Better size aligning?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
sizealigningbetter

Problem

I have the following two vectors in C++11:

vector left = { 1, 2, 3, 4, 5, 6 }; // it is meant to represent the number: 123456
vector right = { 1, 2, 3, 4 }; // meant to be number: 1234


After a function processes them, they become:

left = { 6, 5, 4, 3, 2, 1 };
right = { 4, 3, 2, 1 };


Now, I need to complete the shorter one with zeros at the end until they are equal in size(). I have thefollowing method:

void bigint::process_operands( vector & left, vector & right )
{
    size_t left_size = left.size();
    size_t right_size = right.size();

    if( left_size < right_size )
    {
        size_t size_diff = right_size - left_size;

        for( size_t i = 0; i != size_diff; ++i )
            left.push_back( '0' );
    } else if( right_size < left_size )
    {
        size_t size_diff = left_size - right_size;

        for( size_t i = 0; i != size_diff; ++i )
            right.push_back( '0' );
    }
}


Is there any better implementation?

Solution

Firstly, given that you're using vector without namespace qualification (that is, not as std::vector), I assume you have a using namespace std; in this code. This is generally a bad idea, but especially so in this case. You use vector & right (and vector left), however, there is a std::right (and a std::left) defined in `. This could potentially lead to some very confusing compiler errors.

Using a few tricks from
`, we can shorten the above code considerably.

void bigint::process_operands(vector & left_, vector & right_)
{
   auto& shorter = (left_.size() < right_.size()) ? left_ : right_;
   std::fill_n(std::back_inserter(shorter), std::abs(left_.size() - right_.size()), '0');
}


This is much more terse, but I find that using the standard library actually makes this code easier to read and more clear as to exactly what it is doing.

Code Snippets

void bigint::process_operands(vector<unsigned char> & left_, vector<unsigned char> & right_)
{
   auto& shorter = (left_.size() < right_.size()) ? left_ : right_;
   std::fill_n(std::back_inserter(shorter), std::abs(left_.size() - right_.size()), '0');
}

Context

StackExchange Code Review Q#43844, answer score: 11

Revisions (0)

No revisions yet.