Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

C++: Write the code for a function object named CompareBits that overloads opera

ID: 3820890 • Letter: C

Question

C++:

Write the code for a function object named CompareBits that overloads operator() such that:

• The method signature is: bool operator() (const int& lhs, const int& rhs)

• Given an object CompareBits comp;

- comp(x,y) returns true if the number of bits that are 1 in x is less than the number of bits that are 1 in y.

- comp(x,y) returns false if the number of bits that are 1 in x is greater than or equal to the number of bits that are 1 in y.

Submit your code for class CompareBits in a file named A6-comp.hpp

Explanation / Answer

#include <iostream>
#include <string>
#include <bitset>
#include <algorithm>
using namespace std;

class CompareBits {
private:
public:

bool operator()(const int &a, const int &b) {
  
//code to convert integer into bits
std::bitset<16> p(a);
std::bitset<16> q(b);
  
//code to convert bits into String
string mystring1 = p.to_string<char,char_traits<char>,allocator<char> >();
string mystring2 = q.to_string<char,char_traits<char>,allocator<char> >();
  
//code to count the number of one's in individual Strings
size_t n1 = std::count(mystring1.begin(), mystring1.end(), '1');
size_t n2 = std::count(mystring2.begin(), mystring2.end(), '1');
  
//code for comparison
if(int(n1)<int(n2)){
return true;
}
return false;
}
      

  
};

int main() {
CompareBits g;
cout<< g(7,8);
return 0;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote