0 day streak
cpp / intermediate
Snippet

Optimized References in Loops

When iterating over containers of objects like strings, using a 'const reference' avoids expensive copy operations for every iteration.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <vector>
#include <string>
void process(const std::vector<std::string>& list) {
for (const std::string& item : list) {
// Read item without copying
}
}
int main() {
std::vector<std::string> data = {"Hello", "World"};
process(data);
return 0;
}
Breakdown
1
const std::string& item
Prevents copying the string object into the loop variable, improving performance.
2
const
Ensures the loop variable cannot modify the original contents of the vector.