Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a for loop like this considered bad practice? [closed]

Tags:

c++

for-loop

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.

like image 299
Jimmy_Rustle Avatar asked Mar 19 '17 03:03

Jimmy_Rustle


People also ask

Is for loop bad practice?

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.

Is it bad practice to use for loops in Python?

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.

IS for loop in a for loop bad?

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.

Why is a for I loop so bad?

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.


1 Answers

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.

like image 56
Thomas Avatar answered Oct 09 '22 22:10

Thomas