C++ – Print Out Objects From Set

In C++11, why use a for loop when you can use a foreach loop?

#include <iostream> //for std::cout

void foo()
{
    for (Person const& person : personList)
    {
        std::cout << person << ' ';
    }
}

In C++98/03, why use a for loop when you can use an algorithm instead?

#include <iterator> //for std::ostream_iterator
#include <algorithm> //for std::copy
#include <iostream> //for std::cout

void foo()
{
    std::copy(
        personList.begin(),
        personList.end(),
        std::ostream_iterator(std::cout, " ")
        );
}

Note that this works with any pair of iterators, not only those from std::set<t>std::copy will use your user-defined operator<< to print out every item inside the set using this single statement.

Leave a Comment

deneme bonusu veren sitelerbahis casinomakrobetceltabetpinbahispolobetpolobet girişpinbahis girişmakrobet girişpulibet girişmobilbahis girişkolaybet giriş