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:
$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")
);
}