2

I'm trying to print every element inside a vector like this:

vector<users>::iterator i;

for(i = userlist.begin(); i<userlist.end(); i++)
{
        cout << *i << "\n";
}

Then I'm getting an error like this:

no match for 'operator<<' in 'std::cout << (&i)->__gnu_cxx::__normal_iterator<_Iterator, _Container>::operator* [with _Iterator = users*, _Container = std::vector<users, std::allocator<users> >]()' 

Is it anything obvious I've missed?

user709712
  • 243
  • 1
  • 6
  • 13

5 Answers5

6

Have you defined a function with this signature?:

std::ostream & operator<<(std::ostream &, const users &);

It should not be a member function of users, although it may or may not be a friend, up to you. The prototype should go in the header file of class users, and the body should go in the source(.cpp) file. I have no idea how your users class is defined, or how you would want to format the output, but the function definition should look something like this:

std::ostream & operator<<(std::ostream & os, const users & U)
{
    os << U.some_data_members;
    os << U.and_or_some_member_functions();
    os << whatever;
    return os;
}
Benjamin Lindley
  • 98,924
  • 9
  • 191
  • 266
2

Once you've defined std::ostream &operator<<(std::ostream &, user&);, consider changing your code to use std::copy instead of a for loop:

// leaving off the `std::`, you're not using it for `cout`.
// 
copy(userlist.begin(), userlist.end(), ostream_iterator<user>(cout, "\n"));
Jerry Coffin
  • 455,417
  • 76
  • 598
  • 1,067
1

Have you defined stream operator for the users class? If not, do so.

levis501
  • 3,941
  • 21
  • 22
1

You need to write an overload of ostream::operator<<() that takes a an instance of users, or write some conversion operator that will provide an auto-conversion from user to some type that one of the operator<<() versions knows about.

QuantumMechanic
  • 13,537
  • 3
  • 41
  • 66
1

You need to define your own public function operator<< taking parameters of an ostream and a users:

std::ostream& operator<<(std::ostream&, users&);

Sorry, is it users or user?

quamrana
  • 33,740
  • 12
  • 54
  • 68
  • It's `users`, but I guess I'll change it, looks better with `user`. But where do I define the function? In the header of the user class? And do I have to create a function inside the user class aswell? – user709712 Apr 18 '11 at 19:40
  • You usually declare the function in the header just below the user class, and define it in the module file alongside the user member functions. – quamrana Apr 18 '11 at 19:51