Let's say we have this function, where vec1 and vec2 store the same kind of data:
int myFunc(vector<int>& vec1, vector<int>& vec2) {
for (auto const& elem : vec1) {
// do something
}
for (auto const& elem : vec2) {
// do the same thing
}
}
Clearly, duplicating code is not great. However, the following is not a solution:
int myFunc(vector<int>& vec1, vector<int>& vec2) {
for (auto const& vec : {vec1, vec2}) {
for (auto const& elem : vec) {
// do something
}
}
}
Doing so would result in a deep copy of vec1 and vec2, which is not what we want. I don't see a way to use pointers here as the vectors are passed in by reference (let's assume we can't change the function signature).
So how do we do the same thing to vec1 and vec2 without duplicating code?