I would say that this is not a bad practice, but it is also not a very good practice.
As Jett's answer pointed out, this can be simplified to
std::vector<int> firstHalf(original.begin(), original.begin() + original.size() / 2); std::vector<int> secondHalf(original.begin() + original.size() / 2, original.end());
I would probably try to avoid recalculating original.size()/2 .
std::size_t halfsize = original.size()/2; std::vector<int> firstHalf(original.begin(), original.begin() + halfsize); std::vector<int> secondHalf(original.begin() + halfsize, original.end());
or even,
std::vector<int>::const_iterator halfway = original.begin() + original.size()/2; std::vector<int> firstHalf(original.begin(), halfway); std::vector<int> secondHalf(halfway, original.end());
(In C ++ 11 and later, halfsize and halfway declarations can use auto to determine type).
Whether they are better or not (e.g. readability) is very subjective.
It is significant that it is recommended to use standard algorithms in which the result is cleaner code and there is obvious equivalence. Adding an extra variable to avoid duplicate expressions can help in readability.
If you really have to use loops for some reason (for example, you do more than just copy parts of a vector to other vectors), then consider:
- use
reserve() before multiple calls to push_back() - use iterators for vector, not for text signature
- precompute reusable values (for example,
std::size_t halfsize = original.size()/2 before the loop, and not repeatedly calculate original.size()/2 inside the loop). This is especially true if original not const , because - depending on what your loop does - the compiler is less likely to determine that it does not change in size. - Use a standard algorithm inside a loop, rather than inject a nested loop.
Peter
source share