I was given this piece of code, which calculates the length of the longest string
in a vector
of string
s:
static size_t max_line_length(std::vector<std::string> &lines) {
size_t max = 0;
for (auto it = lines.begin(); it != lines.end(); it++) {
if (it->length() > max) {
max = it->length();
}
}
return max;
}
I am new to C++ with a significant background in Java. If I would write such a function myself, I would come up with something like:
static size_t max_line_length(std::vector<std::string> lines) {
size_t max = 0;
for (auto line : lines) {
if (line.length() > max) {
max = line.length();
}
}
return max;
}
The difference is in the use of pointers, and the way in iterating the string
s.
Is there a significant performance difference between these implementations, or are there best practices involved in this?
auto
toconst auto&
in the loop, otherwise every line will be needlessly copied. – Morwenn Dec 6 '14 at 15:28const std::vector<std::string> &lines
as well? Also, if you could write your comment in a nice little answer, I can accept it :) – nhaarman Dec 6 '14 at 15:45vector
would be a constant, but not thestring
s themselves, right? So this would allow the function to manipulate thestring
s, whereas the original method would be pure. – nhaarman Dec 6 '14 at 15:47