C ++ - Print objects from a set

If I have a C ++ suite and an iterator:

set<Person> personList; set<Person>::const_iterator location; 

How to print the contents of a set? These are all objects of a person, and I overloaded the operator <for a person.

The line where the errors are in the base for the loop:

 cout << location 

Netbeans gives:

proj.cpp: 78: error: no match for 'operator <<<in' std :: cout <location

It looks like he wants to overload for the iterator operator <

Basically, I take objects that were previously saved in an array format, but are now in a set. What is the equivalent of cout << array[i] for sets?

+4
source share
3 answers

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 the loop for , 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 just std::set<t> . std::copy will use your custom operator<< to print each element inside set using this single operator.

+10
source

You need to dereference the iterator:

  std::cout << *location; 

The agreement to use the indirection or dereference operator to obtain a reference value for an iterator was chosen similarly to the pointers:

  person* p = &somePerson; std::cout << *p; 
+5
source

this is set :: iterator

  for(it = output_set.begin(); it != output_set.end(); it++) { outstream_1 << *it << endl; } 
+5
source

Source: https://habr.com/ru/post/1309181/


All Articles