KaiserJohaan
KaiserJohaan

Reputation: 9240

BOOST_FOREACH and a vector

I have a vector of Scenes, vector<Scene>. What is the correct way to iterate over the elements, as reference or not?

For example this:

BOOST_FOREACH(Scene scene, mScenes)
{
       .....
}

Does the macro copy the Scene for each iteration over the vector, or does it use a reference behind the scenes?

So is it any different from this:

BOOST_FOREACH(Scene& scene, mScenes)
{
       .....
}

Upvotes: 2

Views: 11526

Answers (3)

Tristram Gr&#228;bener
Tristram Gr&#228;bener

Reputation: 9711

Note that with C++11 you don't need to use BOOST_FOREACH (excepted with some boost libs that return a pair of iterators).

for(const Scene& scene: mScenes){}

The same rules apply as for BOOST_FOREACH : you most likely want to use const &, rarely &, and never copy.

Upvotes: 2

David Schwartz
David Schwartz

Reputation: 182743

Your first example does copy each Scene. Most likely, you want the second. With the first, you can modify scene and the vector will be unaffected. If you're not modifying the vector, you should use const Scene& scene. If you are, use Scene &.

Upvotes: 5

kassak
kassak

Reputation: 4184

BOOST_FOREACH behaves exactly as you tell him, by value, reference or const reference

Upvotes: 9

Related Questions