-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
  • what does `count->first` refer to ? Is it a `ChildInfo` object. If yes, then how are you supposed to print is without overloading the `<< operator` – PRP Sep 23 '16 at 06:29
  • Cut this down to a [mcve] and you'll see it has absolutely nothing to do with counting duplicates or maps. – juanchopanza Sep 23 '16 at 06:33
  • @PRP why do I need to overload the << operator?? – Hmmmmm Sep 23 '16 at 06:35
  • @iksemyonov answer explains what I told in the comments. See that. – PRP Sep 23 '16 at 06:37

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,068
  • 1
  • 20
  • 40
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
  • 718
  • 7
  • 12