0

I was studying structures and came across this problem.

#include<iostream>
#include<string>
#include<vector>


using namespace std;

struct entry
{
    string name;
    int number;
};


int main()
{
    vector<entry> adres{{"Noname",212345},{"Yesname",7564745}};

    for(x:adres)
    {
        cout<<x<<endl;
    }

}

This is just a test code!

SO I created a struct and wanted to use that in my vector. C++ gave me this error

error: no match for 'operator<<' (operand types are 'std::ostream {aka std::basic_ostream<char>}' and 'entry')|

After some searching I found that I needed to Overload << operator to output my Vector with my defined data type.

My question is how can I do that? How can I overload " << " so that I can output my vector. I know the concepts of Operator Overloading but this one just seems too confusing. Is there any way I can just use " << " sign to output for user defined types?

NoobLearner
  • 61
  • 1
  • 6
  • *"This is just a test code!"* - Can you please post code that displays *only* the problem you ask about? `for(x:adres)` isn't a well-formed loop and causes a completely unrelated error. Please read some more about creating a [mcve]. – StoryTeller - Unslander Monica Aug 26 '18 at 13:12

1 Answers1

2

You can overload << operator like this.

std::ostream& operator<<(std::ostream& out, const entry& e) {
    out << "Name: " << e.name << ", Number: " << e.number;
    return out;
}
Mohit
  • 1,225
  • 11
  • 28