If I have a C++ set and iterator:
set<Person> personList;
set<Person>::const_iterator location;
How can I print out the contents of the set? They are all person objects, and I have overloaded operator<< for Person.
The line that errors is in a basic for loop:
cout << location
Netbeans gives:
proj.cpp:78: error: no match for ‘operator<<’ in ‘std::cout << location’
It looks like it wants an overload for the iterator's operator<<.
Basically, I am taking objects that used to be stored in an array format, but are now in a set. What is the equivalent to cout << array[i]
for sets?
You need to dereference the iterator:
std::cout << *location;
The convention of using the indirection or dereferencing operator to get the referenced value for an iterator was chosen in analogy to pointers:
person* p = &somePerson;
std::cout << *p;
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.
it is a set::iterator
for(it = output_set.begin(); it != output_set.end(); it++)
{
outstream_1 << *it << endl;
}
begin() is a built-in function in C++ STL function which used to return an iterator pointing to the first element of the set container.
end() is a built-in function in C++ STL which is used to get an iterator to past the last element. The past-the-end element is the theoretical element that would follow the last element in the vector. It does not point to any element, and thus shall not be dereferenced.
Also, the objects in Set are distinct values stored in ascending or descending order.
example 1:
set<char> myset{'a', 'c', 'g', 'z'};
for (auto it=myset.begin(); it != myset.end(); ++it)
cout << ' ' << *it;
output : a c g z
example 2:
set<string> myset{"This", "is", "confused"};
for (auto it=myset.begin(); it != myset.end(); ++it)
cout << ' ' << *it;
output : This confused is
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With