unnnn unnnn - 1 month ago 10
C++ Question

counting duplicates using map c++

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.


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.