Use std::bitsetif your function set is less than the number of bits in the long (I think it's long), you can get an unsigned long representation of the bits, then two values, and use the twidling bit tricks here to count.
If you want to continue using strings to represent your bit pattern, you can do something like the following using zip_iteratorfrom boost.
#include <iostream>
#include <string>
#include <algorithm>
#include <boost/tuple/tuple.hpp>
#include <boost/iterator/zip_iterator.hpp>
struct check_is_set :
public std::unary_function<const boost::tuple<char const&, char const&>&, bool>
{
bool operator()(const boost::tuple<char const&, char const&>& t) const
{
const char& cv1 = boost::get<0>(t);
const char& cv2 = boost::get<1>(t);
return cv1 == char('1') && cv1 == cv2;
}
};
size_t count_same(std::string const& opt1, std::string const& opt2)
{
std::string::const_iterator beg1 = opt1.begin();
std::string::const_iterator beg2 = opt2.begin();
size_t end_s = std::min(opt1.size(), opt2.size());
std::string::const_iterator end1 = opt1.begin() + end_s;
std::string::const_iterator end2 = opt2.begin() + end_s;
return std::count_if(
boost::make_zip_iterator(
boost::make_tuple(beg1, beg2)
),
boost::make_zip_iterator(
boost::make_tuple(end1, end2)
),
check_is_set()
);
}
int main(void)
{
std::string opt1("1010111");
std::string opt2("001101");
std::cout << "same: " << count_same(opt1, opt2) << std::endl;
return 0;
}
source
share