So for this example, say I have a std::vector called original and I want to split it in half into two different vectors. Assume original has an even amount of elements.
std::vector<int> firstHalf;
std::vector<int> secondHalf;
for (int i = 0, j = original.size()/2; i < original.size() / 2; i++, j++)
{
firstHalf.push_back(original[i]);
secondHalf.push_back(original[j]);
}
The more obvious way to do this would be to have two separate for loops, one to fill up firstHalf and one to fill up secondHalf.
Is writing the for loop like I did considered bad practice? From my testing, this solution is slightly more efficient than having two separate for loops.
It is not in good practice because of two things: for loops are meant to iterate over a collection of data. a for loop consists of iterator initial state, loop condition and an iterating function that are related.
Actually, it is a bad practice in Python to use for loops, list comprehensions, or . apply() in pandas. Instead, you should always prefer array computations.
Nested loops are frequently (but not always) bad practice, because they're frequently (but not always) overkill for what you're trying to do. In many cases, there's a much faster and less wasteful way to accomplish the goal you're trying to achieve.
for loops--and while loops-- are what's known as control statements, meaning they must be placed inside of a function and can not be used as standalones. This inherently increases the chance you'll end up manipulating variables outside of the loop's scope.
In fact, you can reduce your code to two lines:
std::vector<int> firstHalf(original.begin(), original.begin() + original.size() / 2);
std::vector<int> secondHalf(original.begin() + original.size() / 2, original.end());
Reason:
push_back
may reallocate memory while the number of elements increasing. stl would allocate enough memory once at the beginning time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With