Help with Object of your Affections

You have std::vector<std::string> hobbies, but the << ostream operator doesn’t have behavior defined for the vector<string> type (that is what the error does say in the very beginning (error: no match for << and vector<basic_string> etc)).

Ok, that’s the error. Now what do you do? That’s really up to what you need.

  • For debugging purposes I highly recommend either getting used to an IDE debugger or GDB. This would allow you to “read” what’s in the vector when debugging.
  • If you need to print it in a special way according to your class, you can overload the << operator and define a special behavior. For example, maybe every time you cout << hobbies you might want it to display 1. hobby_a, 2. hobby_b, in some neat sort of way by default.
  • You just need to print the dang thing to standard out. Then you have to think, ok, vector is not printable, what’s the next best thing? Ah, the strings inside themselves. So you do a loop and print out each item in the loop.

One possible way

for (const auto& hobby: hobbies)
{
    std::cout << hobby << "\n";
}

A couple of things to note here. The use of const &, very important and useful to read up (exercise left to the reader). Also the use of auto. Also the use of range-based loops. Also the use of \n over std::endl. Happy hacking.

PS: Is this a bit much? Well C++ is a technical language, so it is good to sink in on details where other languages abstract it away. Particularly for games where performance is important it’s pretty nice to know what exactly is happening.

3 Likes