Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C++: Store the count before iteration, or call .size() every time?

I’m first time with C++ and I have a question about storing the "count" in a variable and calling .size().

Why did I have this question? Because I have an internal contradiction!

In all other languages ​​that I have used, be it php, typescript or python, I have always written the count to a variable before iteration, because in all these languages ​​it is considered good practice, php for example:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$count = count($arr);
for($i = 0; $i < $count; $i++) ...

But! I’ve looked at different sources of various open source c++ projects and you guys who use c++ seem to always do like this:

for (std::size_t i = 0; i < bt.size() && i < BACKTRACE_HASHED_LENGTH; i++) {
    h = h * 0x4372897893428797lu + reinterpret_cast<std::uintptr_t>(bt[i]);
}

So, is it okay for C++ to always use .size()? Or how do you do it?

>Solution :

If the collection is not mutated in the loop (and that way lies madness) then a size member function should return a constant, and a smart enough compiler will figure this out and optimize away the performance concern you have.

However, a modern C++ programmer would likely look for an iterator based approach rather than what you’ve shown, and thus sidestep the whole issue.

#include <iostream>
#include <vector>

int main() {
    std::vector<int> vec { 1, 2, 3, 4, 5, 6, 7 };

    for (std::size_t i = 0; i < vec.size(); i++) {
        std::cout << vec[i] << std::endl;
    }
}

As opposed to:

#include <iostream>
#include <vector>

int main() {
    std::vector<int> vec { 1, 2, 3, 4, 5, 6, 7 };

    for (auto &x : vec) {
        std::cout << x << std::endl;
    }
}

Or going another step along this line.

#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>

int main() {
    std::vector<int> vec { 1, 2, 3, 4, 5, 6, 7 };

    std::copy(
      vec.cbegin(), vec.cend(),
      std::ostream_iterator<int>(std::cout, "\n")
    );
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading