我的以下字符串试图找出两个字符串之间的区别.但它迭代字符串的长度非常慢:
#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)
这应该快得多,因为没有创建新的字符串.
有趣的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)