Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
232 views
in Technique[技术] by (71.8m points)

c++ - How to iterate over several objects passed by reference?

Let's say we have this function, where vec1 and vec2 store the same kind of data:

int myFunc(vector& vec1, vector& 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& vec1, vector& 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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It's fairly simple to use std::reference_wrapper to avoid making a deep copy, and pretty much do the same thing what you wanted to do originally:

#include 
#include 
#include 

int myFunc(std::vector& vec1, std::vector& vec2) {
    for (auto const& vec : {std::ref(vec1), std::ref(vec2)}) {
        auto const &real_vec=vec.get();

        for (auto const& elem : real_vec) {
        }
    }
    return 0;
}

int main()
{
    std::vector vec1, vec2;

    myFunc(vec1, vec2);
    return 0;
}

No deep copies.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...