-1

I'm trying to count duplicates using map and I'm using vector of struct.

I keep having error at this part:

void display(const std::map<ChildInfo, unsigned int>& counts) {
    for (auto count = counts.begin(); count != counts.end(); ++count) {
        std::cout << "Value " << count->first << " has count " << count->second << std::endl;
    }
}

the error is about << operand but I have no idea how to fix this.

Hmmmmm
  • 79
  • 1
  • 1
  • 6

2 Answers2

1

Define an overload of the operator<<() for the ChildInfo struct:

std::ostream& operator<<(std::ostream& str, const ChildInfo& ci) {
    str << "id " <<  ci.id << " gram " << ci.gram << "\n";
    return str;
}

When the compiler encounters std::cout << count->first, then operator<<(std::ostream,&, ChildInfo&) is called, that's now C++ operators work. (Precisely, this code equivalents to operator<<(std::cout, count->first)) But there is no overload of the said operator for your struct ChildInfo. It's only defined for basic types and for standard library types, but as far as the latter goes, that was done by the library developers the same way as shown above. So, define it to fix the error.

See Operator overloading for reference.

Also do get in the habit of specifying the exact error message that you're getting. A programmer, or any engineer for that matter, must be precise, else it's not going to work, period.

Community
  • 1
  • 1
iksemyonov
  • 4,106
  • 1
  • 22
  • 42
0

In the function display, you want to display ChildInfo elements (the count->first elements of the map, but you did not defined an operator << for this class.

A simple solution is to add something like

ostream& operator << (ostream & os, const ChildInfo& lhs) 
{ 
    os << lhs.id; 
    return os; 
}

Of course, you can change the content to be displayed.

Ionel POP
  • 743
  • 7
  • 12