Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

should I use the algorithm or hand-code it in this case?

Ok, someone tell me which would be better. I need to |= the elements of one vector with another. That is, I want to

void orTogether(vector<char>& v1, const vector<char>& v2)
{
    typedef vector<char>::iterator iter;
    for (iter i = v1.begin(), iter j = v2.begin() ; i != v1.end(); ++i, ++j)
        *i |= *j;
}

I can't use for_each due to needing to process 2 collections. I suppose I could do something like

struct BitWiseOr
{
    char operator()(const char& a, const char& b) {return a | b;}
};

void orTogether2(vector<char>& v1, const vector<char>& v2)
{
    transform(v1.begin(), v1.end(), v2.begin(), 
        v1.begin(), BitwiseOr());
}

Is this a more efficient solution even though the top one is in place, but the bottom is an assign? This is right in the middle of a processing loop and I need the fastest code possible.

Edit: Added (obvious?) code for BitwiseOr. Also, I'm getting a lot of comments on non-related things like checking the lengths of v2 and changing the names. This is just an example, the real code is more complicated.

Well, I profiled both. orTogether2 is much faster than orTogether, so I'll be going with the transform method. I was surprised, orTogether2 was about 4 times faster in MSVC9 release mode. I ran it twice, changing the order the second time to make sure it wasn't some sort of cache issue, but same results. Thanks for the help everyone.

like image 909
rlbond Avatar asked Nov 29 '22 20:11

rlbond


2 Answers

The bottom one will compile to effectively the same as the first, your OR functor is going to be inlined for sure. So the second idiom is more flexible if you ever need to add more flexibility or debugging frameworks or whatever.

Since there's no benefit to the first, use the transform method. Once you get into that habit you'll stop even considering the explicit loop choice for all your apps since it's unnecessary. The only advantage to the first method is it's easier to explain to beginner C++ programmers who are more comfortable with raw C.

like image 167
SPWorley Avatar answered Dec 05 '22 08:12

SPWorley


Grab your watch and measure

like image 31
Robert Gould Avatar answered Dec 05 '22 07:12

Robert Gould