用于查找字符串差异的位操作

nev*_*int 6 c++ string

我的以下字符串试图找出两个字符串之间的区别.但它迭代字符串的长度非常慢:

#include <string>
#include <vector>
#include <iostream>
using namespace std;


int hd(string s1, string s2) {
    // hd stands for "Hamming Distance"
    int dif = 0;

    for (unsigned i = 0; i < s1.size(); i++ ) {
        string b1 = s1.substr(i,1);
        string b2 = s2.substr(i,1);

        if (b1 != b2) {
            dif++;
        }
    }  

    return dif;
}

int main() {

    string string1 = "AAAAA";
    string string2 = "ATATT";
    string string3 = "AAAAA";

    int theHD12 = hd(string1,string2);
    cout << theHD12 << endl;

    int theHD13 = hd(string1,string3);
    cout << theHD13 << endl;
}
Run Code Online (Sandbox Code Playgroud)

有没有这样做的快速替代方案?在Perl中,我们可以采用以下方法:

sub hd {
    return ($_[0] ^ $_[1]) =~ tr/\001-\255//;
}
Run Code Online (Sandbox Code Playgroud)

这比迭代位置快2倍.

我想知道它在C++中的含义是什么?

sch*_*der 12

尝试通过以下方式替换for循环:

for (unsigned i = 0; i < s1.size(); i++ ) {
    if (b1[i] != b2[i]) {
            dif++;
    }
}  
Run Code Online (Sandbox Code Playgroud)

这应该快得多,因为没有创建新的字符串.


Éri*_*ant 9

有趣的STL:

#include <numeric>    //inner_product
#include <functional> //plus, equal_to, not2
#include <string>   
#include <stdexcept>

unsigned int 
hd(const std::string& s1, const std::string& s2)
{
    // TODO: What should we do if s1.size() != s2.size()?
    if (s1.size() != s2.size()){
      throw std::invalid_argument(
          "Strings passed to hd() must have the same lenght"
      );
    }

    return std::inner_product(
        s1.begin(), s1.end(), s2.begin(), 
        0, std::plus<unsigned int>(),
        std::not2(std::equal_to<std::string::value_type>())
    );
}
Run Code Online (Sandbox Code Playgroud)

  • @gsamaras:在其基本版本中,inner_product计算两个范围A和B的乘积之和:A [0]*B [0] + A [1]*B [1] + ...在广义版本中(在这里使用),两个操作(加法和乘法)由调用者提供.我们在这里想要的是不同的元素对的数量,所以我们仍然希望第一个操作是加法(std :: plus),但我们希望第二个操作是"不相等"(std :: not( std :: equal_to))而不是乘法. (3认同)